rhughes
rhughes

Reputation: 9583

C++: Bitwise AND

I am trying to understand how to use Bitwise AND to extract the values of individual bytes.

What I have is a 4-byte array and am casting the last 2 bytes into a single 2 byte value. Then I am trying to extract the original single byte values from that 2 byte value. See the attachment for a screen shot of my code and values.

The problem I am having is I am not able to get the value of the last byte in the 2 byte value.

How would I go about doing this with Bitwise AND?

Bitewise AND

Upvotes: 1

Views: 855

Answers (3)

The problem I am having is I am not able to get the value of the last byte in the 2 byte value.

Your 2byte integer is formed with the values 3 and 4 (since your pointer is to a[1]). As you have already seen in your tests, you can get the 3 by applying the mask 0xFF. Now, to get the 4 you need to remove the lower bits and shift the value. In your example, by using the mask 0xFF00 you effectively remove the 3 from the 16bit number, but you leave the 4 in the high byte of your 2byte number, which is the value 1024 == 2^10 -- 11th bit set, which is the third bit in the second byte (counting from the least representative)

You can shift that result 8 bits to the right to get your 4, or else you can ignore the mask altogether, since by just shifting to the right the lowest bits will disappear:

4 == ( x>>8 )

More interesting results to test bitwise and can be obtained by working with a single number:

int x = 7;              // or char, for what matters:
(x & 0x1) == 1;
(x & (0x1<<1) ) == 2;   // (x & 0x2)
(x & ~(0x2)) == 5;

Upvotes: 5

wholerabbit
wholerabbit

Reputation: 11546

The problem I am having is I am not able to get the value of the last byte in the 2 byte value.

Not sure where that "watch" table comes from or if there is more code involved, but it looks to me like the result is correct. Remember, one of them is a high byte and so the value is shifted << 8 places. On a little endian machine, the high byte would be the second one.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308158

You need to add some bit-shifting to convert the masked value from the upper byte to the lower byte.

Upvotes: 3

Related Questions