简体   繁体   中英

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?

按位与

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;

您需要添加一些位移来将屏蔽值从高字节转换为低字节。

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.

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