如何在C中将int转换为char *(不使用sprintf) [英] How to convert int into char* in C (without sprintf)
问题描述
有一天,我想在C中将整数转换为char *,该int可以为负。
some day, i wanted to convert in C an integer into a char *, this int can be negative.
我无法使用sprintf,snprintf都不是,那我该怎么做?
I wasn't able to use sprintf ,snprintf neither, so how do i do that ?
推荐答案
要滚动一个自己的 itoa()$类似于c $ c>的函数,第一个必须解决如何处理内存。最简单的方法是为所有可能的
int
值( INT_MIN
)使用足够大的内存。
To roll one's own itoa()
-like function, first one must address how to handle memory. The easiest is to use a large-enough memory for all possible int
values (INT_MIN
).
缓冲区所需大小在数学上是 ceiling(log10(-INT_MIN))+ 3
。可以通过以下方式对此进行近似:
The buffer required size is mathematically ceiling(log10(-INT_MIN))+3
. This can be approximated with:
#include <limits.h>
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT/3 + 3)
然后构建位数以最低有效位数开始依次递增,先使用%10
,然后使用 / 10
来减少
Then build the digits up one-by-one starting with the least significant digit using %10
and then /10
to reduce the value.
通过使用 do
循环,代码捕获了 x = = 0
,因为至少要输入一位数字。
By using a do
loop, code catches the corner case of x==0
as at least one digit is made.
此代码避免了 if(x <0){x = -x; ...
取反 INT_MIN
(或乘以-1会导致 int
溢出,
This code avoids if (x < 0) { x = -x; ...
as negating INT_MIN
(or multiplying by -1 leads to int
overflow, which is UB.
#include <limits.h>
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT/3 + 3)
char *my_itoa(char *dest, size_t size, int x) {
char buf[INT_STR_SIZE];
char *p = &buf[INT_STR_SIZE - 1];
*p = '\0';
int i = x;
do {
*(--p) = abs(i%10) + '0';
i /= 10;
} while (i);
if (x < 0) {
*(--p) = '-';
}
size_t len = (size_t) (&buf[INT_STR_SIZE] - p);
if (len > size) {
return NULL; // Not enough room
}
return memcpy(dest, p, len);
}
使用C99或更高版本,代码可以使用复合文字处理缓冲区创建,从而为每个 mt_itoa()$提供单独的缓冲区c $ c>调用。
With C99 or later, code can handle the buffer creation with a compound literal allowing separate buffers for each mt_itoa()
call.
// compound literal C99 or later
#define MY_ITOA(x) my_itoa((char [INT_STR_SIZE]){""}, INT_STR_SIZE, x)
int main(void) {
printf("%s %s %s %s\n", MY_ITOA(INT_MIN), MY_ITOA(-1), MY_ITOA(0), MY_ITOA(INT_MAX));
return (0);
}
输出
-2147483648 -1 0 2147483647
这篇关于如何在C中将int转换为char *(不使用sprintf)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!