2011-06-21 73 views
2

下面的簡單代碼產生奇怪輸出:printf的字節到十六進制字符串奇怪輸出

#include <stdio.h> 
#include <string.h> 
#include "/tmp/sha.h" 
#define DIGEST 64 

//taken from coreutils 8.5 - produces 64-byte sha digest and puts it into resblock 
extern int sha512_stream(FILE *stream, void *resblock); 

int main(int argc, char** argv) { 

char sha[DIGEST]; 
memset(sha, 0, DIGEST); 
FILE *stream; 
stream = fopen("/bin/less", "r"); 
sha512_stream(stream, (void *) sha); 
fclose(stream); 

char buf[2] = {10, 32}; 
printf("%02x\n", sha[0]); 
printf("%02x\n", buf[0]); 

return 0;} 

給出的輸出:
ffffffa9
0A

SHA的第一個字節是A9,但在哪裏填補F的來自?

在Ubuntu Linux 10.10上使用gcc 4.4.5。

回答

7

(char)默認爲(signed char)在Linux x86,因爲printf()使用stdarg(signed char)被隱式提升爲(int)導致符號擴展。您需要聲明(unsigned char)才能獲得預期的行爲。 (沒有辦法通過stdarg傳遞類型信息,因此默認促銷是在參數上執行的。)

+0

我對您的知識印象深刻。謝謝,問題解決了。 – abirvalg

相關問題