簡體   English   中英

C中的unsigned long和atoi

[英]unsigned long and atoi in C

碼:

char temp[] = "1010000001010011";
printf("%s\n", temp);
unsigned long num = atoi(temp);
printf("%lu\n", num);

輸出:

1010000001010011
4081617243

為什么num不是41043?

atoi("1010000001010011"); 嘗試將文本作為十進制字符序列轉換為int 如果int足夠寬,它將采用十進制值1,010,000,001,010,011。 毫不奇怪,該值超出了OP的int范圍,因此結果是未定義的行為或UB。

若要將字符串轉換為二進制字符,請使用strtol()strtoul()

char temp[] = "1010000001010011";
char *endptr;
int base = 2;
unsigned long ulnum = strtoul(temp, &endptr, base);
if (endptr == temp) puts("No conversion");
else printf("%lu\n", ulnum);  // 41043

atoi返回一個int值。 十進制數1010000001010011 (十六進制39696F348895B不適合32位變量,並被截斷為十六進制F348895B即帶符號十進制值-213350053 但是,盡管該編譯器生成的代碼確實分配了該位模式,但unsigned long碰巧是4081617243 ,但是將該值分配給unsigned long是不確定的行為。

非常感謝@AnT和@chux

Beacouse atoi()將字符串轉換為整數,而不是從二進制轉換。 例如代碼

char str[]="123";
printf("%d",atoi(str));

將輸出123為整數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM