java之二進位與資料類型(一)

來源:互聯網
上載者:User

標籤:cto   十六進位   color   運算   使用字串   ring   方式   shadow   integer   

一、java支援十進位、八進位和十六進位,但是不支援二進位

java支援十進位:

java表示十進位不需要對數字有任何處理

//java表示十進位int a = 13;System.out.println("java表示十進位:"+a);

運行結果:

java支援八進位:

java表示八進位時,以“0”打頭

//java表示八進位int b = 013;System.out.println("java表示八進位:"+b);

運行結果:

java支援十六進位

java表示十六進位時,以“0x”打頭

//java表示十六進位int c = 0x13;System.out.println("java表示十六進位:"+c);

運行結果:

java不顯式支援二進位

因為二進位過長,java中只能使用字串來表示二進位

二、java運算方式

上面介紹了,java支援十進位、八進位、十六進位,但是細心的小夥伴馬上就發現了,上面的運行結果並不是我們所要的指定進位的數字,而是統一以十進位的形式標表示,這就說明,java在運算時始終使用二進位作為運算方法。

三、進位轉換

整型轉換為字串

首先聲明一個十進位的整型數字:

int result = 13;

十進位->八進位

//將result由十進位轉為八進位String octalStr = Integer.toOctalString(result);System.out.println(octalStr);

運行結果:

十進位->十六進位

//將result由十進位轉為十六進位String hexStr = Integer.toHexString(result);System.out.println(hexStr);

運行結果:

十進位->二進位

//將result由十進位轉為二進位String binaryStr = Integer.toBinaryString(result);System.out.println(binaryStr);

運行結果:

字串轉為整型:

Interger.valueOf(字串,進位)方法可以將十進位轉為其他進位的整型表示

String resultStr = "13";//轉為八進位result = Integer.valueOf(resultStr, 8);System.out.println("轉為八進位:"+result);result = Integer.valueOf(resultStr,16);System.out.println("轉為十六進位:"+result);

運行結果:

那麼,現在我們將retultStr轉為二進位會發生什麼呢?

result = Integer.valueOf(resultStr,2);System.out.println("轉為二進位:"+result);

運行結果:

事實證明,java真的不能以整數形式表示二進位

java之二進位與資料類型(一)

聯繫我們

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