简体   繁体   中英

Shifting bits java

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?

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;

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

it says, "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 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. eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM