我試圖在32位機器上執行十六進制到整數的轉換。這裏是我與測試代碼,將十六進制字符串轉換爲長
int main(int argc,char **argv)
{
char *hexstring = "0xffff1234";
long int n;
fprintf(stdout, "Conversion results of string: %s\n", hexstring);
n = strtol(hexstring, (char**)0, 0); /* same as base = 16 */
fprintf(stdout, "strtol = %ld\n", n);
n = sscanf(hexstring, "%x", &n);
fprintf(stdout, "sscanf = %ld\n", n);
n = atol(hexstring);
fprintf(stdout, "atol = %ld\n", n);
fgetc(stdin);
return 0;
}
這是我得到什麼:
strtol = 2147483647 /* = 0x7fffffff -> overflow!! */
sscanf = 1 /* nevermind */
atol = 0 /* nevermind */
正如你看到的,與strtol將我得到的溢出(我還檢查與錯誤號),但我會預計不會發生,因爲0xffff1234是一個有效的整數32位值。 我會期望4294906420或其他-60876
我錯過了什麼?
你確定設置基數爲0是16。我的意思是替換* strtol(hexstring,(char **)0,0)* * strtol(hexstring,(char **)0,* * 16 **)* – 2012-07-24 09:48:16
@AG設置基數爲0意味着'strtol'試圖從輸入字符串的開頭找出它自己,無論是使用16,10或8的數字。 – 2012-07-24 10:14:42
對,我忘了!謝謝 ! – 2012-07-24 13:11:41