嵌入式C中的源代码,用于无符号整数到字符串

没有使用标准库utoa,我正在寻找utoa的源代码,所以我可以为特定项目定制它。 我有无符号整数(32位),输出如0xFFFF_FFFF

我也在寻找二进制格式的无符号整数和半字到字符串的源代码。

试试这个:

 char *dec(unsigned x, char *s) { *--s = 0; if (!x) *--s = '0'; for (; x; x/=10) *--s = '0'+x%10; return s; } 

用一个指向调用者提供的缓冲区末尾的指针调用它,该函数返回指向字符串开头的指针。 缓冲区的长度至少应为3*sizeof(int)+1 ,以确保安全。

当然,这很容易适应其他基础。

在谷歌上很容易找到很多itoa源文件…那应该给你你想要的东西,例如。 itoa来自opensource.apple.com

或者从头开始写它,这不是太难。

这不是特别难。 保持除以10并使用余数mod 10作为“0123455679”的索引。 你从右到左构建它,所以你必须缓冲结果并反过来返回它:

 char * utoa(unsigned int n) { char * res, buf[30]; // long enough for largest number unsigned int i, counter = 0; if (n == 0) buf[counter++] = '0'; for ( ; n; n /= 10) buf[counter++] = "0123456789"[n%10]; res = malloc(counter); for (i = 0; i < counter; ++i) res[i] = buf[counter - i - 1]; return res; } 
 #include  #include  char * utox(uint32_t n) { static char hexstr[sizeof(n)*2+1]; char * p = hexstr + sizeof(hexstr) -1; int x; memset(hexstr, '0', sizeof(hexstr)); *p-- = '\0'; while (n) { x = n % 16; if (x < 10) *p-- = '0' + x; else *p-- = 'A' + x - 10; n /= 16; } return hexstr; } 

这应该做,它是零垫。 只需更改函数参数中的n类型,即可使其适用于任何整数类型/大小。

这里提到/建议的大多数function都使用模数%运算符,这对嵌入式系统来说非常昂贵。

所以使用除以10的想法是我猜的唯一突出的选择。 这里是:

 /*for byte which is 3 digit most*/ void itoa(unsigned char value,char *desitination) { desitination[0] = '\0'; desitination[1] = '\0'; desitination[2] = '\0'; desitination[3] = '\0';//you at least 4 char array, last char is NULL while (value >= 100) { desitination[0]++; value -= 100; } desitination[1] = '0'; while (value >= 10) { desitination[1]++; value -= 10; } value+= '0'; desitination[2] =value; } 

itoa有很多实现。 这是其中之一,从2到36考虑基础:

 /** * C++ version 0.4 char* style "itoa": * Written by Lukás Chmela * Released under GPLv3. */ char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } 

这里可以找到更多变化,其包括各种实现的速度性能。