public class PrintBits
1: // Fig. I.2: PrintBits.java
2: // Printing an unsigned integer in bits.
3: import java.util.Scanner;
4:
5: public class PrintBits
6: {
7: public static void main( String args[] )
8: {
9: // get input integer
10: Scanner scanner = new Scanner( System.in );
11: System.out.println( "Please enter an integer:" );
12: int input = scanner.nextInt();
13:
14: // display bit representation of an integer
15: System.out.println( "\nThe integer in bits is:" );
16:
17: // create int value with 1 in leftmost bit and 0s elsewhere
18: int displayMask = 1 << 31;
19:
20: // for each bit display 0 or 1
21: for ( int bit = 1; bit <= 32; bit++ )
22: {
23: // use displayMask to isolate bit
24: System.out.print( ( input & displayMask ) == 0 ? '0' : '1' );
25:
26: input <<= 1; // shift value one position to left
27:
28: if ( bit % 8 == 0 )
29: System.out.print( ' ' ); // display space every 8 bits
30: } // end for
31: } // end main
32: } // end class PrintBits
33:
34:
35: /**************************************************************************
36: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
37: * Pearson Education, Inc. All Rights Reserved. *
38: * *
39: * DISCLAIMER: The authors and publisher of this book have used their *
40: * best efforts in preparing the book. These efforts include the *
41: * development, research, and testing of the theories and programs *
42: * to determine their effectiveness. The authors and publisher make *
43: * no warranty of any kind, expressed or implied, with regard to these *
44: * programs or to the documentation contained in these books. The authors *
45: * and publisher shall not be liable in any event for incidental or *
46: * consequential damages in connection with, or arising out of, the *
47: * furnishing, performance, or use of these programs. *
48: *************************************************************************/