2011-12-16 174 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'; 
} 
相關問題