首页 > 代码库 > 待解:用二进制形式显示任何整数的二进制值
待解:用二进制形式显示任何整数的二进制值
1 package com.java7.showbitsdemo; 2 /* 3 * Try This 5-3 4 * A class that displays the binary representation of a value. 5 */ 6 class ShowBits { 7 int numbits; 8 9 ShowBits(int n) {10 numbits = n;11 }12 13 void show(long val) {14 long mask = 1;15 16 // left-shift a 1 into the proper position17 mask <<= numbits-1;18 19 int spacer = 0;20 for(; mask != 0; mask >>>=1) {21 if((val & mask) != 0) System.out.print("1");22 else System.out.print("0");23 spacer++;24 if((spacer % 8) == 0) {25 System.out.print("");26 spacer = 0;27 }28 }29 System.out.println();30 }31 }32 33 // Demonstrate ShowBits.34 class ShowBitsDemo {35 public static void main(String[] args) {36 ShowBits b = new ShowBits(8);37 ShowBits i = new ShowBits(32);38 ShowBits li = new ShowBits(64);39 System.out.println("123 in binary: ");40 b.show(123);41 42 System.out.println("\n87987 in binary: ");43 i.show(87987);44 45 System.out.println("\n237658768 in binary: ");46 li.show(237658768);47 48 // you can also show low-order bits of any integer49 System.out.println("\nLow order 8 bits of 87987 in binary: ");50 b.show(87987);51 }52 }
执行结果:
123 in binary:
01111011
87987 in binary:
00000000000000010101011110110011
237658768 in binary:
0000000000000000000000000000000000001110001010100110001010010000
Low order 8 bits of 87987 in binary:
10110011
待解:用二进制形式显示任何整数的二进制值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。