c++ 進位轉換函式

來源:互聯網
上載者:User

標籤:font   int   定向   base   print   article   iostream   style   進位   

轉自:78690248

 

strtol 函數:

 

它的功能是將一個任意1-36進位數轉化為10進位數,返回是long int型。

 

函數為long int strtol(const char *nptr, char **endptr, int base)

 

base是要轉化的數的進位,非法字元會賦值給endptr,nptr是要轉化的字元,例如:

char buffer[20]="10379cend$3";char *stop;printf("%d\n",strtol(buffer, &stop, 8));printf("%s\n", stop);

輸出結果:
543
9cend$3

將一個8進位轉化為10進位,讀取1037,其他後面的為非法字元,轉化結果以int型輸出來。

另外,如果base為0,且字串不是以0x(或者0X)開頭,則按十進位進行轉化。如果base為0或者16,並且字串以0x(或者0X)開頭,那麼,x(或者X)被忽略,字串按16進位轉化。如果base不等於0和16,並且字串以0x(或者0X)開頭,那麼x被視為非法字元。

最後,需要說明的是,對於nptr指向的字串,其開頭和結尾處的空格被忽視,字串中間的空格被視為非法字元。

 

c++中還有一些定向的轉換:

std::bitset(轉2進位),std::oct(轉8進位),std::dec (轉10進位),std::hex(轉16進位)。

#include <bitset>#include <iostream>using namespace std;int main(){    cout << "36的8進位:" << std::oct << 36 << endl;    cout << "36的10進位" << std::dec << 36 << endl;    cout << "36的16進位:" << std::hex << 36 << endl;    cout << "36的2進位: " << bitset<8>(36) << endl;    return 0;}

 

c++ 進位轉換函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.