package class9_3_BitwiseAnd_start;// Dr. Yoder. MSOE. 10 February 2017 public class BitwiseAndExample { public static final int BITS_IN_INT = 32; public static final int BITS_IN_BYTE = 8; public static void main(String[] args) { int i = 255; System.out.println("i = " + i); System.out.println("contents: "+ showBits(i)); // for debugging only! byte b = (byte)i; System.out.println("b = " + b); System.out.println("contents: "+ showBits(b)); // for debugging only! int i2 = b; System.out.println("i2 = " + i2); System.out.println("contents: "+ showBits(i2)); // for debugging only! int i3 = 0xff & b; System.out.println("i3 = " + i3); System.out.println("contents: "+ showBits(i3)); // for debugging only! } /** * Convert a byte into a string * where each character of the string shows one bit * that is actually stored for that byte. * @param b the byte to show * @return the string as described above */ private static String showBits(byte b) { String bits = Integer.toBinaryString(Byte.toUnsignedInt(b)); int bitsToAdd = BITS_IN_BYTE -bits.length(); for(int index = 0; index < bitsToAdd; index++) { bits = "0"+bits; } return bits; } /** * Convert an int into a string * where each character of the string shows one bit * that is actually stored for that byte. * @param i the int to show * @return the string as described above */ private static String showBits(int i) { String bits = Integer.toBinaryString(i); int bitsToAdd = BITS_IN_INT -bits.length(); for(int index = 0; index < bitsToAdd; index++) { bits = "0"+bits; } return bits; } }