您好,登錄后才能下訂單哦!
將一個整數(shù)轉(zhuǎn)化成二進(jìn)制的方法:
1 方法1:使用BigInteger類:
@Test public void test1(){ BigInteger b=new BigInteger("10");//1010 System.out.println(b.toString(2));//0 b=new BigInteger("1"); System.out.println(b.toString(2));//1 b=new BigInteger("255"); System.out.println(b.toString(2));//11111111 b=new BigInteger("254"); System.out.println(b.toString(2));//11111110 }
2 方法2:使用Integer.toBinaryString():
@Test public void test(){ String str2 = Integer.toBinaryString(0); System.out.println(str2);//0 str2 = Integer.toBinaryString(1); System.out.println(str2);//1 str2 = Integer.toBinaryString(255); System.out.println(str2);//11111111 }
如上,確實(shí)能夠?qū)⒁粋€整數(shù)轉(zhuǎn)化成二進(jìn)制,但是不足之處在于當(dāng)一個數(shù)被轉(zhuǎn)化成二進(jìn)制時不足8位時,不會自動補(bǔ)0;
所以要獲得8位二進(jìn)制數(shù)時,要加上判斷:
@Test public void test3(){ String tempStr = ""; String str2 = Integer.toBinaryString(10); //判斷一下:如果轉(zhuǎn)化為二進(jìn)制為0或者1或者不滿8位,要在數(shù)后補(bǔ)0 int bit = 8-str2.length(); if(str2.length()<8){ for(int j=0; j<bit; j++){ str2 = "0"+str2; } } tempStr += str2; System.out.println(tempStr); }
總結(jié)
以上就是本文關(guān)于java將一個整數(shù)轉(zhuǎn)化成二進(jìn)制代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。