不使用标准库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
。buf + sizeof buf
。在我看来,这是C语言中“end”的标准习惯用法;另一种版本具有类似于基于1的索引的偏移量问题。 - R.. GitHub STOP HELPING ICE/*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;
}
这并不是非常困难。不断地除以10,并使用余数模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;
}
malloc
的答案打-1的冲动... - R.. GitHub STOP HELPING ICE'0'+n%10
多出 一条 汇编指令...) - Kerrek SB-fPIC
,它也可以将GOT寄存器依赖(用于相对寻址)引入到本来完全是位置无关的函数中。 - R.. GitHub STOP HELPING ICE#include <stdint.h>
#include <string.h>
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
类型,即可使其适用于任何整数类型/大小。
有许多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;
}
更多变体可以在这里找到,其中包括各种实现的速度性能。
utoa
不是 C 标准库的一部分。(也许它是你的libc
实现的一部分,但不是标准。) - Chris Lutz