C ++:按位与 [英] C++: Bitwise AND

查看:83
本文介绍了C ++:按位与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何使用按位AND提取单个字节的值.

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

我有一个4字节的数组,并将最后2个字节转换为一个2字节的值.然后,我尝试从该2个字节的值中提取原始的单字节值.有关我的代码和值的屏幕截图,请参见附件.

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.

我遇到的问题是我无法获取2字节值中的最后一个字节的值.

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

我将如何使用Bitwise AND来做到这一点?

How would I go about doing this with Bitwise AND?

感谢您的帮助,

Richard Hughes

Richard Hughes

推荐答案

我遇到的问题是我无法获取2字节值中的最后一个字节的值.

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

您的2字节整数由值3和4组成(因为您的指针指向a[1]).正如您在测试中已经看到的那样,可以通过应用掩码0xFF来获得3.现在,要获取4,您需要删除较低的位,并移动该值.在您的示例中,通过使用掩码0xFF00,您可以有效地从16位数字中删除3,但是将4保留在2字节数字的高字节中,该值是值1024 == 2^10-第11位设置,它是第二个字节中的第三位(从最小代表数开始计数)

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)

您可以将结果右移8位以获取4,否则可以完全忽略掩码,因为仅向右移最低位将消失:

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;

这篇关于C ++:按位与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆