2011-12-16 175 views
0

任何人都可以告诉我什么是下面的代码错?数据类型转换(无符号long long到char)

__inline__ 
char* ut_byte_to_long (ulint nb) { 

    char* a = malloc(sizeof(nb)); 
    int i = 0; 
    for (i=0;i<sizeof(nb);i++) { 
     a[i] = (nb>>(i*8)) & 0xFF; 
    } 
    return a; 
} 

此字符串然后再连接到如使用strcat一个较大的一个的一部分。字符串可以很好地打印,但用于表示为字符符号的整数。我正在使用%sfprintf检查结果。

非常感谢。

编辑

我把下面的意见之一(我是单独加入终止\0,呼吁fprintf之前,但strcat后修改我最初的功能...

__inline__ 
char* ut_byte_to_long (ulint nb) { 

    char* a = malloc(sizeof(nb) + 1); 
    int i = 0; 
    for (i=0;i<sizeof(nb);i++) { 
     a[i] = (nb>>(i*8)) & 0xFF; 
    } 
    a[nb] = '\0' ; 
    return a; 
} 

这示例代码仍未打印出数字...

char* tmp; 
tmp = ut_byte_to_long(start->id); 

fprintf(stderr, "Value of node is %s \n ", tmp); 
+1

“string”? ???终止零字节在哪里? – pmg 2011-12-16 23:36:14

+1

你只是将数字`nb`分解成字节(小端),所以它是一种与字符串/文本不兼容的二进制格式。如果你选择了小数字,你肯定会在那里有一些零字节。 – u0b34a0f6ae 2011-12-16 23:40:56

回答

1

如果您不想使用sprintf(target_string,"%lu",source_int)或非标准itoa(),以下是将长变换为字符串的函数版本:

__inline__ 
char* ut_byte_to_long (ulint nb) { 
    char* a = (char*) malloc(22*sizeof(char)); 
    int i=21; 
    int j; 
    do 
    { 
     i--; 
     a[i] = nb % 10 + '0'; 
     nb = nb/10; 
    }while (nb > 0); 
    // the number is stored from a[i] to a[21] 

    //shifting the string to a[0] : a[21-i] 
    for(j = 0 ; j < 21 && i < 21 ; j++ , i++) 
    { 
     a[j] = a[i]; 
    } 
    a[j] = '\0'; 
    return a; 
} 

我假定一个无符号长整型包含少于21个数字。 (最大数字是18,446,744,073,709,551,615,等于2^64 - 1:20数字)

4

strcat期望空字节终止字符串。

将您的malloc尺寸更改为sizeof(nb) + 1并附加'\0'到最后。

2

你有两个问题。

首先,字符数组a包含代替代表这些数字的ASCII码的数字,例如2,如'2'(= 50上ASCII,可能是在其他系统不同)。尝试修改您的代码以

a[i] = (nb>>(i*8)) & 0xFF + '0'; 

第二个问题是,上述计算的结果可以是0到255之间的任何东西,或者换句话说,打印数量,需要一个以上的数字。

如果要打印的十六进制数字(0-9,AF),每个这样的计算两个数字就足够了,你可以写类似

a[2*i + 0] = int2hex((nb>>(i*8)) & 0x0F); //right hexa digit 
a[2*i + 1] = int2hex((nb>>(i*8+4)) & 0x0F); //left hexa digit 

其中

char int2hex(int n) { 
    if (n <= 9 && n >= 0) 
    return n + '0'; 
    else 
    return (n-10) + 'A'; 
} 
相关问题