// Binary.java
// Description: Example of using binary operations

public class Binary {

    public static void main(String []args) {

        // Imagine we asked you to make a copy of bits 5-7 to bits 0-2,
        // leaving bits 3-4 untouched. This is very similar to the swap
        // image from your programming assignment. The code shown here is
        // for one pixel, of course you would have to put this code inside
        // a nested loop to process an entire image. Remember that bit 0
        // is the least significant and bit 7 is the most significant.
        
        // For example, oldPixel = 0b11010011 would transform to newPixel = 0b11010110
        // You can change the binary literals to check other values

        // oldPixel = imageData[row][col];
        int oldPixel = 0b11010011;
        
        // STEP ONE: Extract bits 5-7 from old pixel
        int bits5to7 = oldPixel & 0b11100000;
        
        // STEP TWO: Extract bits 3-4 from old pixel
        int bits3to4 = oldPixel & 0b00011000;

        // STEP THREE: Move bits 5-7 to 0-2 by shifting right
        int bits0to2 = bits5to7 >> 5;
        
        // STEP FOUR: Combine bits into new pixel
        int newPixel = bits5to7 | bits3to4 | bits0to2;
        // imageData[row][col] = newPixel;
        
        // Now print old and new pixels
        System.out.println("Old pixel = 0b" + Integer.toBinaryString(oldPixel));
        System.out.println("New pixel = 0b" + Integer.toBinaryString(newPixel));
    }
}

© 2014 CS160 Colorado State University. All Rights Reserved.