Take the 2-minute tour ×

To insert the value, start by using a mask to clear out the 8-bits of the pixel corresponding to the given color channel. For example, in the case of red, shift an 8-bit mask of ones left 16 bits, invert it (using the ~ operator), and “and” (&) this mask with the RGB value, which clears out the 8 bits of red and leaves the other bits unchanged. Next, shift the parameter value (red, in this case) left the same number of bits (16, in the case of red) and “or” (|) the shifted value into the pixel value.

int getRed(){
    red = (Pixel>>16);
    red = ~Pixel;
    red = Pixel<<16 | Pixel;
    return red;

What am I doing wrong according to the directions?

share|improve this question
you should be re-using the red value in subsequent operations. since red is always being assigned from some operation on Pixel, you aren't accumulating the 3 operations, just doing 3 independent operations. –  jtahlborn Oct 7 '13 at 1:48
You're assigning three different values to "red". The results from the first two are overlaid by the third, so that's the only one you get. –  Hot Licks Oct 7 '13 at 1:57

2 Answers 2

The problem here seems to be a fundamental problem in understanding how assignment works (in Java ... and just about every imperative programming language!). For example:

red = (Pixel>>16);
red = ~Pixel;

That says:

  1. Assign to red the value of Pixel shifted by 16 bits

  2. Assign to red the value of Pixel negated bitwise. This clobbers the value of red that you calculated in the previous step.

If you want to negate the value that you calculated in step 1, then you need to do this:

red = ~red;
share|improve this answer

I believe you simply don't understand what's going on. The very first line is already incorrect:


Which means

8 bit mask of ones:  0xFF  (00000000 00000000 00000000 11111111)
shift left 16 bits:  0xFF << 16  (giving you  00000000 11111111 00000000 00000000)
invert it         :  ~ (0xFF << 16)  (giving you (11111111 00000000 11111111 11111111)
& this mask with RGB value:  result = pixel & (~(0xFF << 16))

The result is the pixel with 17th-24th bit cleared.

That's the first step (yes there are subsequent steps, as described in your homework) to set the "Red" value in pixel

I am not sure if it is your intention but what you developed has nothing to do with your question: instead of setting red value, it seems you are getting red value.

However, still, what you developed is still far from correct. e.g. you should have a similar mask with 17th-24th bits being 1 and other bits being 0, then & the pixel with this mask, and then shift the remaining value (which located at 17th-24th bits) to 0-7th bits.

I am not going to give you the actual answer because it is your work to learn from it. However I believe the hints I gave is more than enough.

share|improve this answer

Your Answer


