C++: Bitwise AND

痞子三分冷 提交于 2019-12-10 00:28:28

问题


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?

Thanks for your help,

Richard Hughes


回答1:


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;



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/10373240/c-bitwise-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!