[英]C Programming: Convert Hex Int to Char*
My question is how I would go about converting something like: 我的问题是我将如何转换如下内容:
int i = 0x11111111;
to a character pointer? 一个字符指针? I tried using the itoa() function but it gave me a floating-point exception. 我尝试使用itoa()函数,但它给了我一个浮点异常。
itoa
is non-standard. itoa
是非标准的。 Stay away. 远离。
One possibility is to use sprintf
and the proper format specifier for hexa ie x
and do: 一种可能性是使用sprintf
和hexa即x
的正确格式说明符并执行:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
However, the problem with this computing the size of the value
array. 但是,这个计算value
数组大小的问题。 You have to do with some guesses and FAQ 12.21 is a good starting point. 你需要做一些猜测和FAQ 12.21是一个很好的起点。
The number of characters required to represent a number in any base b
can be approximated by the following formula: 表示任何基数b
的数字所需的字符数可以通过以下公式近似:
⌈log b (n + 1)⌉ ⌈日志b (n + 1)⌉
Add a couple more to hold the 0x
, if need be, and then your BIG_ENOUGH
is ready. 如果需要,再添加几个来保持0x
,然后你的BIG_ENOUGH
就绪了。
char buffer[20];
Then: 然后:
sprintf(buffer, "%x", i);
Or: 要么:
itoa(i, buffer, 16);
Character pointer to buffer can be buffer
itself (but it is const) or other variable: 缓冲区的字符指针可以是buffer
本身(但它是const)或其他变量:
char *p = buffer;
Using the sprintf() function like this -- sprintf(charBuffer, "%x", i);
使用像这样的sprintf()函数 - sprintf(charBuffer, "%x", i);
-- I think will work very well. - 我认为会很好。
Using the sprintf()
function to convert an integer to hexadecimal should accomplish your task. 使用sprintf()
函数将整数转换为十六进制应该可以完成您的任务。
Here is an example: 这是一个例子:
int i = 0x11111111;
char szHexPrintBuf[10];
int ret_code = 0;
ret_code = sprintf(szHexPrintBuf, "%x", i);
if(0 > ret_code)
{
something-bad-happend();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.