字串轉換成數字以及注意事項,字串注意事項

來源:互聯網
上載者:User

字串轉換成數字以及注意事項,字串注意事項

將字串轉換成數字:

有符號轉換需要用到atoi,atol,atoll等。無符號轉換需要使用strtoul和strtoull等。

(1)常用的轉換函式

轉換出來的是有符號的:

#include <stdlib.h>

int atoi(cosnt char *nptr);

long atol(const char* nptr);

long long atoll(const  char*nptr);

long long atoq(const  char*nptr);

long int strtol(const char*nptr,const  char**endptr,int base);

long long int strtoll(const char* nptr,char** endptr,int base);

轉換出來的是無符號的:               

unsigned long int strtoul(const char*nptr,char** endptr,int base);

unsigned long long int strtoull(const char* nptr,char**endptr,int base);

(2)情境問題

unsigned int  value  = (unsigned int)atoi("3000000000");

printf("value = %u",value);

在64位機器下,value=3000000000。然而在32位機器下value=2147483647

因為atoi函數內部還是使用strtol實現的,則在atoi內部首先是strtol將"3000000000"轉換成long類型,

在64位機器下,long是8位元組的,最高位是符號位,資料位元是63位。

而在32位機器下,long是4位元組的,最高位元組是符號位,資料位元是31位。則在有符號轉換函式strtol會將"3000000000"轉換時截短為2147483647(有符號數四位元組數正數的最大值,即位元 0111 1111 1111 1111 1111 1111 1111 1111)。

使用strtoul可正確處理(對於4位元組無符號的數有效)。

同理,對於8位元組無符號的數,需要使用strtoull,否則即使使用atoll來轉換,也會存在同樣的問題(無論是64位機器還是32位機器)。

使用代碼如下:

Example
12345678910111213141516
/* strtoull example */#include <stdio.h>      /* printf, NULL */#include <stdlib.h>     /* strtoull */int main (){  char szNumbers[] = "250068492 7b06af00 1100011011110101010001100000 0x6fffff";  char * pEnd;  unsigned long long int ulli1, ulli2, ulli3, ulli4;  ulli1 = strtoull (szNumbers, &pEnd, 10);//該數為10進位數  ulli2 = strtoull (pEnd, &pEnd, 16);//該數為16進位數  ulli3 = strtoull (pEnd, &pEnd, 2);//該數為2進位數  ulli4 = strtoull (pEnd, NULL, 0);//該數根據首碼的指定進位數  printf ("The decimal equivalents are: %llu, %llu, %llu and %llu.\n", ulli1, ulli2, ulli3, ulli4);  return 0;}



Output:
The decimal equivalents are: 250068492, 2064035584, 208622688 and 7340031.


 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.