1 方法1:使用BigInteger類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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():
1
2
3
4
5
6
7
8
9
10
11
|
@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 } |
如上,確實能夠?qū)⒁粋€整數(shù)轉(zhuǎn)化成二進制,但是不足之處在于當一個數(shù)被轉(zhuǎn)化成二進制時不足8位時,不會自動補0;
所以要獲得8位二進制數(shù)時,要加上判斷:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Test public void test3(){ String tempStr = "" ; String str2 = Integer.toBinaryString( 10 ); //判斷一下:如果轉(zhuǎn)化為二進制為0或者1或者不滿8位,要在數(shù)后補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); } |
總結
以上就是本文關于java將一個整數(shù)轉(zhuǎn)化成二進制代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/noaman_wgs/article/details/52629603