位比较合理 [英] Rational comparison of bits

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

问题描述

我有一些int类型。它位于[0,255]内。也就是说,包括8位。我需要经常检查说:

2(INT)= 00000010(二进制)


  1,第6位和第7位必须等于分别为0和1。
  我检查它是这样的:


 如果(((informationOctet_&安培;!(1 LT;< 6)))及及(informationOctet_及(1 LT; 7;)))
{
    ...
}

但它不是非常具有可读性,是否有可能 - 能做些什么美?
我不能使用的std :: bitset的,我的头说,这是资源的浪费,你不能没有它。


解决方案

有两种合理的解决办法:要么将所有鸵鸟政策关注位到零,然后测试结果,或设置鸵鸟政策关注位一个和测试结果如下:

 (X安培;将0xC0)== 0x80的
(X |〜将0xC0)==〜0X40

由于哈罗德在评论中指出,第一种形式是更为常见。这种模式是很常见的,你的编译器的优化器将识别它。

其他的形式存在,但他们模糊的:((X ^ 0x80的)及将0xC0 == 0)作品一样好,但目前还不太清楚。一些ISA的不能直接加载大的常量,所以他们用的等价((X>> 6)及0x3中)== 0X2 。不要用这种麻烦,您优化器会。

I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say:

2(int) = 00000010(Binary)

  1. The bit 6 and bit 7 must be equal to 0 and 1 respectively. 
  And I check it like this:

if ((!(informationOctet_ & (1 << 6))) && (informationOctet_ & (1 << 7)))
{
    ...
}

But it is not very readable, whether it is possible - to do something "beautiful"? I can not use the std::bitset, my head says it's a waste of resources and you can not do without it.

解决方案

There are two reasonable solutions: either set all don't-care bits to zero, and then test the result, or set the don't-care bits to one and test the result:

(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40

As harold pointed out in the comment, the first form is far more common. This pattern is so common that the optimizer of your compiler will recognize it.

Other forms exist, but they're obscure: ((x ^ 0x80) & 0xC0 == 0) works just as well but is less clear. Some ISA's cannot load large constants directly, so they use the equivalent of ((x>>6) & 0x3) == 0x2. Don't bother with this, your optimizer will.

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

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