问题描述
我的问题是我将如何转换如下内容:
My question is how I would go about converting something like:
int i = 0x11111111;
到一个字符指针?我尝试使用 itoa() 函数,但它给了我一个浮点异常.
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
推荐答案
itoa
是非标准的.远离.
一种可能性是使用 sprintf
和正确的十六进制格式说明符,即 x
并执行:
One possibility is to use sprintf
and the proper format specifier for hexa i.e. x
and do:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
然而,这个计算 value
数组大小的问题.您必须进行一些猜测,FAQ 12.21 是一个很好的起点.
However, the problem with this computing the size of the value
array. You have to do with some guesses and FAQ 12.21 is a good starting point.
在任何基本 b
中表示一个数字所需的字符数可以通过以下公式近似:
The number of characters required to represent a number in any base b
can be approximated by the following formula:
⌈log(n + 1)⌉
如果需要,再添加几个来保存 0x
,然后您的 BIG_ENOUGH
就准备好了.
Add a couple more to hold the 0x
, if need be, and then your BIG_ENOUGH
is ready.
这篇关于C 编程:将 Hex Int 转换为 Char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!