将achex值转换为char *

如何将c中的hex值转换为等效的char*值。 例如,如果hex值为1df2则char *也应包含1df2

我正在使用VinC编译器和来自FTDIVNC2 USB ChipVinL链接器。 它有以下头文件; stdlibstdiostring 。 这些是主要c库的子集,并没有明显的答案,如snprintfsprintf

文档说以下类型是有效的,

对于在整个内核和驱动程序中使用的变量和函数类型,存在某些定义。 它们可用于vos.h头文件中的应用程序。

空指针和逻辑定义:

 #define NULL 0 #define TRUE 1 #define FALSE 0 

变量类型定义:

 #define uint8 unsigned char #define int8 char #define int16 short #define uint16 unsigned short #define uint32 unsigned int #define pvoid unsigned char * 

function类型定义:

 typedef uint8 (*PF)(uint8); typedef void (*PF_OPEN)(void *); typedef void (*PF_CLOSE)(void *); typedef uint8 (*PF_IOCTL)(pvoid); typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *); typedef void (*PF_INT)(void); 

有什么建议?

使用snprintf()

 int to_hex(char *output, size_t len, unsigned n) { return snprintf(output, len, "%.4x", n); } 

鉴于新信息它是一个相当基本的嵌入式系统,那么如果你只对16位数字感兴趣,这样的最小解决方案可能就足够了:

 /* output points to buffer of at least 5 chars */ void to_hex_16(char *output, unsigned n) { static const char hex_digits[] = "0123456789abcdef"; output[0] = hex_digits[(n >> 12) & 0xf]; output[1] = hex_digits[(n >> 8) & 0xf]; output[2] = hex_digits[(n >> 4) & 0xf]; output[3] = hex_digits[n & 0xf]; output[4] = '\0'; } 

(应该清楚如何将其扩展到更宽的数字)。

试试sprintf :

 int to_hex(char *output,unsigned n) { return sprintf(output, "%.4x", n); } 

它不如caf的答案安全,但如果你有stdio应该工作。 因此,您必须确保输出缓冲区足够大以容纳结果字符串。

这样的事情应该这样做:

 void to_hex(char *buffer, size_t size, unsigned n) { size_t i; size_t j; char c; unsigned digit; // Print digits in the reverse order for (i = 0; i < size - 1; ++i) { digit = n & 0xf; buffer[i] = digit < 10 ? digit + '0' : digit - 10 + 'A'; n >>= 4; if (n == 0) { break; } } // Append NUL buffer[i + 1] = 0; // Reverse the string for (j = 0; j < i / 2; ++j) { c = buffer[j]; buffer[j] = buffer[i - j]; buffer[i - j] = c; } } 

但是你说你有stdio可用,所以不需要自己写这样的东西。

编辑:可能是编译器期望K&R样式原型:

 void to_hex(buffer, size, n) char *buffer; size_t size; unsigned n; { ... 

在Codepad上试试吧。