因此,我正在編寫一個非常小而簡單的程序,它將一個數字作爲輸入,將其轉換爲十六進制,並一次打印出兩個字符。C - 在十六進制中打印出一個字符指針會給我奇怪的結果
對於某些數字,它會在輸出前打印出ffffff。
這是我的代碼:
//Convert the input to an unsigned int
unsigned int a = strtoul (argv[1], NULL, 0);
//Convert the unsigned int to a char pointer
char* c = (char*) &a;
//Print out the char two at a time
for(int i = 0; i < 4; i++){
printf("%02x ", c[i]);
}
大部分輸出的是罰款,看起來像這樣:
./hex_int 1
01 00 00 00
但對於一些數字輸出看起來是這樣的:
./hex_int 100000
ffffffa0 ffffff86 01 00
如果你刪除所有的f的轉換是正確的,但我不明白爲什麼它只在一些輸入這樣做。
任何人有任何想法?
可能重複[爲什麼printf在打印十六進制時不打印一個字節?](http://stackoverflow.com/questions/3555791/why-does-printf-not-print-out-just-one-byte-when-printing-hex) –
不是你的問題的原因,但因爲'strtoul '返回一個'unsigned long',你可能應該聲明'a'是'unsigned long',即使在你的處理器上它可能有或者可能不是相同的大小。 – lurker
@mbratch - 爲了一致性,這是一個好主意,但可能不是絕對必要的。從'unsigned long'到'unsigned int'的轉換是非常明確的。 –