C++11 比特的理性比较

C++11 比特的理性比较,c++11,int,bit-manipulation,bit,C++11,Int,Bit Manipulation,Bit,我有一个int类型的数字。它位于[0255]之内。也就是说,包括8位。我需要经常检查并说: 2int=000000 10二进制 但它不是很可读,是否有可能-做一些美丽的事? 我不能使用std::位集,我的头说这是浪费资源,你不能没有它。你可以应用一些掩蔽技术 int i = 246; // Lets say any value. int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th b

我有一个int类型的数字。它位于[0255]之内。也就是说,包括8位。我需要经常检查并说:

2int=000000 10二进制

但它不是很可读,是否有可能-做一些美丽的事?
我不能使用std::位集,我的头说这是浪费资源,你不能没有它。

你可以应用一些掩蔽技术

int i = 246; // Lets say any value.
int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th bit
if (chk == 2) // because we want to check 6th bit is 0 & 7th is 1, that becomes 2 value in decimal
    printf("The 6th bit is 0 & 7th bit is 1");
else
    printf("Either 6th bit is not 0 or 7th bit is not 1, or both are not 0 & 1 respectivly");

有两种合理的解决方案:要么将所有不关心位设置为零,然后测试结果,要么将不关心位设置为一,然后测试结果:

(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40
正如哈罗德在评论中指出的,第一种形式更为常见。这种模式非常常见,编译器的优化器会识别它


其他形式也存在,但它们并不明确:x^0x80&0xC0==0同样有效,但不太清晰。一些ISA不能直接加载大常量,因此它们使用x>>6&0x3==0x2的等效值。不用担心,优化器会这样做。

是x&0xC0==0x80 ie,通常的方法不够好吗?通常位的编号是LSB 0到MSB 7。此外,据我记忆所及,二进制文字是c++14,如果你说位的编号是从0到7。然后通过将掩码更改为00000011b&将结果与十进制的1进行比较,您也可以找到您的答案。但技术是一样的。@WaqasShabbir:MSB表示最重要的位,即最左边的位。0b00000011具有最右边的LSB集,即位0。
int i = 246; // Lets say any value.
int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th bit
if (chk == 2) // because we want to check 6th bit is 0 & 7th is 1, that becomes 2 value in decimal
    printf("The 6th bit is 0 & 7th bit is 1");
else
    printf("Either 6th bit is not 0 or 7th bit is not 1, or both are not 0 & 1 respectivly");
(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40