1 PackageCom.java7.showbitsdemo;2 /*3 * Try this 5-34 * A class that displays the binary representation of a value.5 */6 classShowbits {7 intnumbits;8 9Showbits (intN) {TenNumbits =N; One } A - voidShowLongval) { - LongMask = 1; the - //Left-shift a 1 into the proper position -Mask <<= numbits-1; - + intSpacer = 0; - for(; Mask! = 0; Mask >>>=1) { + if(Val & mask)! = 0) System.out.print ("1"); A ElseSystem.out.print ("0"); atspacer++; - if((spacer% 8) = = 0) { -System.out.print (""); -Spacer = 0; - } - } in System.out.println (); - } to } + - //demonstrate showbits. the classShowbitsdemo { * Public Static voidMain (string[] args) { $Showbits B =NewShowbits (8);Panax NotoginsengShowbits i =NewShowbits (32); -Showbits Li =NewShowbits (64); theSystem.out.println ("123 in binary:"); +B.show (123); A theSystem.out.println ("\n87987 in binary:"); +I.show (87987); - $System.out.println ("\n237658768 in binary:"); $Li.show (237658768); - - //You can also show low-order bits of any integer theSystem.out.println ("\nlow order 8 bits of 87987 in binary:"); -B.show (87987);Wuyi } the}
Execution Result:
123 in binary:
01111011
87987 in binary:
00000000000000010101011110110011
237658768 in binary:
0000000000000000000000000000000000001110001010100110001010010000
Low order 8 bits of 87987 in binary:
10110011
To be solved: Displays the binary value of any integer in binary form