Jason Koo

      Stay hungry, Stay foolish!

导航

打印输出整数的二进制形式

Posted on 2011-10-15 23:49  Jason Koo  阅读(1222)  评论(0编辑  收藏  举报

 

       Java中有两种不是很常用的操作符:位操作符和移位操作符。这两种操作符都只能用于处理整数类型(char, byte, short, int 和 long)。通过使用这两种运算符可以实现打印输出整数的二进制形式。下面是打印输出整形和长整型的二进制形式的方法。

//打印输出int类型的变量的二进制形式。在java中整型变量占32位

 1 public void printBinaryInt(int i) {
2 for(int j = 31; j >= 0; j-- ) {
3 if( ( (1 << j) & i ) != 0){
4 System.out.print("1");
5 } else {
6 System.out.print("0");
7 }
8 System.out.println();
9 }
10 }

 

 

//打印输出long类型的变量的二进制形式。在java中整型变量占64位

 1 public void printBinaryLong(long l) {
2 for(int i = 63; i >=0; i--) {
3 if( ( (1L << i) & 1 ) != 0 ){
4 System.out.print("1");
5 } else {
6 System.out.print("0");
7 }
8 System.out.println();
9 }
10 }