简体   繁体   English

C++:按位与

[英]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.我拥有的是一个 4 字节数组,并将最后 2 个字节转换为单个 2 字节值。 Then I am trying to extract the original single byte values from that 2 byte value.然后我试图从那个 2 字节值中提取原始的单字节值。 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.我遇到的问题是我无法获得 2 字节值中最后一个字节的值。

How would I go about doing this with Bitwise AND?我将如何使用 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.我遇到的问题是我无法获得 2 字节值中最后一个字节的值。

Your 2byte integer is formed with the values 3 and 4 (since your pointer is to a[1] ).您的 2byte 整数由值 3 和 4 组成(因为您的指针指向a[1] )。 As you have already seen in your tests, you can get the 3 by applying the mask 0xFF .正如您在测试中已经看到的,您可以通过应用掩码0xFF来获得3 Now, to get the 4 you need to remove the lower bits and shift the value.现在,要获得4您需要删除低位移动值。 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)在您的示例中,通过使用掩码0xFF00您可以有效地从 16 位数字中删除3 ,但将4保留在4字节数字的高字节中,即值1024 == 2^10 -- 第 11 位集,即是第二个字节中的第三位(从最不具有代表性的开始计数)

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 :您可以将结果向右移动 8 位以获得4 ,否则您可以完全忽略掩码,因为只需向右移动,最低位就会消失

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.我遇到的问题是我无法获得 2 字节值中最后一个字节的值。

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.请记住,其中一个是高字节,因此该值被移动了 << 8 位。 On a little endian machine, the high byte would be the second one.在小端机器上,高字节将是第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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