如何将 char 数组转换为以十六进制表示其值的字符串?

How can I transform a char array to a string representing its value in hexadecimal?

我正在尝试将字符数组转换为十六进制数数组。 输入数组中的每个字符将被转换为代表相应十六进制数的两个字符。

这是我的输入:

char input[3] = "over";

这将是输出:

char output[6] = "6f766572";

如何在没有库的情况下在 C 中实现这种转换?提前致谢。

我目前的代码如下:

void convert(char *input, int inputsize) {
  char c;
  char output[inputsize * 2];
  for (int i = 0; i < inputsize; i++) {
    c = input[i]
    // change c to hex here
    // put each letter of the hex into output[i * 2] and output[i * 2 + 1]
  }
}

你可以试试这个:

void toHex(const char *in, int len, char *out)
{
    for(int i = 0; i < len; i++)
    {
        sprintf(&out[i * 2], "%x", in[i]);
    }
}

int main(int argc, const char * argv[])
{
    char input[] = "over";
    char output[32];
    memset(output, 0, sizeof(output));
    toHex(input, sizeof(input), output);
    puts(output);
    return 0;
}
  • 创建一个循环 运行,直到它在输入缓冲区中找到 [=10=]
  • 对于输入字符串中的每个字符编号 [i],屏蔽掉该字节的高半字节和低半字节。确保使用无符号类型。
  • 运行两个半字节中的每一个通过查找table例如const char HEX_LOOKUP [16] = "0123456789ABCDEF";,其中半字节的值用作索引。
  • 将结果存储在输出索引 [i*2][i*2+1] 中,因为输出正好是输入的两倍。
  • Null 终止输出字符串。

如果您不想使用库函数,则必须自己构建一个简单的查找table:

#include <stdio.h> // only for printing the result

const char table[] = "0123456789abcdef";

int main(void) {
    char src[5 + 1] = "hello";
    char dst[5 * 2 + 1];
    char *s, *d;

    for (s = src, d = dst; *s != '[=10=]'; s++, d += 2) {
        const unsigned char lo = *s & 0xf;
        const unsigned char hi = *s >> 4;

        *d = table[hi];
        *(d + 1) = table[lo];
    }

    *d = '[=10=]';

    puts(dst);
    return 0;
}