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 }

 



相关文章:

  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-09
  • 2021-07-21
  • 2021-12-06
  • 2021-12-18
  • 2021-12-09
  • 2021-10-25
  • 2022-12-23
相关资源
相似解决方案