[英]Convert a c hex value into a char*
如何將c中的hex
值轉換為等效的char*
值。 例如,如果十六進制值為1df2
則char *還應包含1df2
。
我正在使用FTDI
的VNC2 USB Chip
的VinC
編譯器和VinL
鏈接器。 它具有以下這些頭文件; stdlib , stdio和string 。 但是,這些是主要c庫的子集,沒有明顯的答案,例如snprintf
或sprintf
。
文檔說以下類型有效,
在整個內核和驅動程序中都使用了某些變量和函數類型的定義。 它們可用於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 *
函數類型定義:
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,它應該可以工作。 therefore make sure that the output buffer is big enough to hold the resulting string. 因此,您確保輸出緩沖區足夠大以容納結果字符串。
這樣的事情應該做到:
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上嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.