Java 十進位 轉 二進位、八進位、十六進位__Java

來源:互聯網
上載者:User

JDK中已經幫我們實現了十進位 轉 二進位、八進位、十六進位的功能,使用Integer.toBinaryString(x)、Integer.toOctalString(x)、Integer.toHexString(x) 即可將x轉換為對應的二進位、八進位、十六進位形式。我們也可以通過位移運算來實現求二進位、八進位、十六進位的功能。


範例程式碼

@Testpublic void test02(){//使用JDK實現int x = -99;System.out.println(x+"="+Integer.toBinaryString(x));System.out.println(x+"="+Integer.toOctalString(x));System.out.println(x+"="+Integer.toHexString(x));}@Testpublic void test01(){int x = -99;System.out.println(x+"="+toBin(x));System.out.println(x+"="+toBa(x));System.out.println(x+"="+toHex(x));}/* * 十進位-->二進位 */public String toBin(int num) {return trans(num, 1, 1);}/* * 十進位-->八進位 */public String toBa(int num) {return trans(num, 7, 3);}/* * 十進位-->十六進位 */public String toHex(int num) {return trans(num, 15, 4);}public String trans(int num, int base, int offset) {if (num == 0) {return null;}char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };char[] arr = new char[32];int pos = arr.length;while (num != 0) {int temp = num & base;arr[--pos] = chs[temp];num = num >>> offset;}StringBuilder sb = new StringBuilder();for (int x = pos; x < arr.length; x++) {sb.append(arr[x]);}return sb.toString();}


最近在做項目時需要將一個byte數組 按6bit一組進行重新組合,研究了一下實現了這個功能

實現代碼

@org.junit.Testpublic void test02(){byte b = 65;//byte b = -86;String str = getAllBinaryBits(b);System.out.println(str);}/** * 將每一個位元組轉換為8位二進位字串形式 * @param b * @return */private String getAllBinaryBits(byte b) {StringBuffer sb = new StringBuffer();sb.append((b & 128)==0?0:(b & 128)>>7);sb.append((b & 64)==0?0:(b & 64)>>6);sb.append((b & 32)==0?0:(b & 32)>>5);sb.append((b & 16)==0?0:(b & 16)>>4);sb.append((b & 8)==0?0:(b & 8)>>3);sb.append((b & 4)==0?0:(b & 4)>>2);sb.append((b & 2)==0?0:(b & 2)>>1);sb.append(b & 1);//System.out.println(sb.toString());return sb.toString();}


要轉換byte數組,套上一個for迴圈即可




聯繫我們

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