我想知道如何在没有标准 C 或 C++ 函数的情况下将数字转换为字符串,例如:
char str[20];
int num = 1234;
// How to convert that number to string (str)?
谢谢。
要获得最低位,请使用num % 10
. 要将数字转换为字符,请添加'0'
. 要在处理完后删除最低位,请除以 10 num /= 10;
:。重复直到完成。
假设您正在str
为您的问题预分配缓冲区:
char *itostr(int num, char *str) {
int len = 1;
long tmp = num;
int sign = num < 0;
if (sign) {
str[0] = '-';
tmp = -tmp;
}
while (num/=10) ++len;
str[len+sign] = 0;
while (len--) {
str[len+sign] = '0'+tmp%10;
tmp /= 10;
}
return str;
}
适用于所有人的“接受后的答案”,int
包括INT_MIN
.
static char *intTostring_helper(int i, char *s) {
if (i < -9) {
s = intTostring_helper(i/10, s);
}
*s++ = (-(i%10)) + '0' ;
return s;
}
char *intTostring(int i, char *dest) {
char *s = dest;
if (i < 0) { // If non 2s compliment, change to some IsSignBitSet() function.
*s++ = '-';
}
else {
i = -i;
}
s = intTostring_helper(i, s);
*s = '\0';
return dest;
}
逐个字符转换,例如字符串的最后一个字符是'4',前一个字符是'3',依此类推。使用数学来确定字符,创建“4321”字符串然后旋转它可能更容易。
一个简单的方法是留下很多前导零。我喜欢它,因为它只使用基本代码,并且不需要任何动态内存分配。因此它也应该非常快:
char * convertToString(int num, str) {
int val;
val = num / 1000000000; str[0] = '0' + val; num -= val * 1000000000;
val = num / 100000000; str[1] = '0' + val; num -= val * 100000000;
val = num / 10000000; str[2] = '0' + val; num -= val * 10000000;
val = num / 1000000; str[3] = '0' + val; num -= val * 1000000;
val = num / 100000; str[4] = '0' + val; num -= val * 100000;
val = num / 10000; str[5] = '0' + val; num -= val * 10000;
val = num / 1000; str[6] = '0' + val; num -= val * 1000;
val = num / 100; str[7] = '0' + val; num -= val * 100;
val = num / 10; str[8] = '0' + val; num -= val * 10;
val = num; str[9] = '0' + val;
str[10] = '\0';
return str;
}
当然,您可以对此进行大量调整 - 修改目标数组的创建方式是可能的,例如添加一个表示修剪前导 0 的布尔值。我们可以使用循环来提高效率。这是改进的方法:
void convertToStringFancier(int num, char * returnArrayAtLeast11Bytes, bool trimLeadingZeros) {
int divisor = 1000000000;
char str[11];
int i;
int val;
for (i = 0; i < 10; ++i, divisor /= 10) {
val = num / divisor;
str[i] = '0' + val;
num -= val * divisor;
}
str[i] = '\0';
// Note that everything below here is just to get rid of the leading zeros and copy the array, which is longer than the actual number conversion.
char * ptr = str;
if (trimLeadingZeros) {
while (*ptr == '0') { ++ptr; }
if (*ptr == '\0') { // handle special case when the input was 0
*(--ptr) = '0';
}
for (i = 0; i < 10 && *ptr != '\0'; ++i) {
while (*ptr != '\0') {
returnArrayAtLeast11Bytes[i] = *ptr;
}
returnArrayAtLeast11Bytes[i] = '\0';
}