BitOperations in Java

/* * BitOperations.java * * Author: Dale Reed, 4/29/2010 * Class: CS 107, UIC * * Show how to convert back and forth between an integer value and * the binary equivalent stored as an array of 0's and 1's * * Running this program looks like: Illustrating binary conversion... Using arithmetic show conversions: 0 in binary is: 0 0 0 0 0 0 0 0 1 in binary is: 0 0 0 0 0 0 0 1 2 in binary is: 0 0 0 0 0 0 1 0 3 in binary is: 0 0 0 0 0 0 1 1 4 in binary is: 0 0 0 0 0 1 0 0 5 in binary is: 0 0 0 0 0 1 0 1 6 in binary is: 0 0 0 0 0 1 1 0 7 in binary is: 0 0 0 e0 0 1 1 1 8 in binary is: 0 0 0 0 1 0 0 0 9 in binary is: 0 0 0 0 1 0 0 1 ... Using bit Operators show conversions: 0 in binary is: 0 0 0 0 0 0 0 0 1 in binary is: 0 0 0 0 0 0 0 1 2 in binary is: 0 0 0 0 0 0 1 0 3 in binary is: 0 0 0 0 0 0 1 1 4 in binary is: 0 0 0 0 0 1 0 0 5 in binary is: 0 0 0 0 0 1 0 1 6 in binary is: 0 0 0 0 0 1 1 0 7 in binary is: 0 0 0 0 0 1 1 1 8 in binary is: 0 0 0 0 1 0 0 0 9 in binary is: 0 0 0 0 1 0 0 1 ... Done with program... */ import java.util.Scanner; // for console IO import java.util.Random; // for random number generation public class BitOperations { Scanner keyboard = new Scanner( System.in); final int Limit = 17; // convert numbers from 0 up to this limit public static void main(String[] args) { BitOperations instance = new BitOperations(); instance.doIt(); } public void doIt() { System.out.println("Illustrating binary conversion..."); // display the 0's and 1's of this number in binary. Do this two // ways: 1. using arithmetic, 2. using bit operators int[] bitValues = new int[8]; System.out.println("\n Using arithmetic show conversions: "); for( int value=0; value> (arrayLength - i - 1); // blank out all the other bits except the right-most one. Do // this by a bit-wise AND with the 8-bit value 0000 0001. The // resulting number will be 0 or 1 valueCopy = valueCopy & 1; // store into the array in the ith position bitValues[ i] = valueCopy; }//end for }//end convertIntToBinaryUsingBits(...) public void displayBitValues(int value, int[] bitValues) { // use printf in the line below to line up numbers System.out.printf("%2d in binary is: ", value); for( int i=0; i< bitValues.length; i++) { System.out.print( bitValues[ i] + " "); } System.out.println(); } } //end class BitOperations