我有一个关于c++中的问题的问题。我必须创建一个程序,其中我必须创建Int和cout<lt;在屏幕上";真"如果第三位是1。
我的问题是:我怎么能看到这个数字的第三位是什么;我尝试过比特集,但无法解决。请帮帮我。
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
int x; cin >> x;
if (x % 3 != 0 && bitset<32>(1)[2])
{
cout << "TRUE";
}
else
{
cout << "FALSE";
}这应该做得对吗?
检查是否设置了给定的位是在许多代码库中都会遇到的经典模式。因此,即使在现代C++中有更干净的方法可以做到这一点,当它出现时,至少能够识别出老派模式仍然是值得的:
// You will typically see bit masks predefined in constants or an enum.
enum flags {
FEATURE_1 = 1 << 0, // first bit
FEATURE_2 = 1 << 1, // second bit
FEATURE_3 = 1 << 2, // third bit
FEATURE_4 = 1 << 3, // fourth bit
};
if(value & FEATURE_3) {
// the bit is set
}
else {
//the bit is not set
}
说明:
(1 << bit_index)
:这将创建一个掩码。也就是说,一个只有我们关心的比特的值。例如1 << 3
是作为8比特整数的0b00001000
。
val & mask
:这在值和掩码之间执行二进制AND,如果并且仅当未设置位时,掩码将为0。由于任何非零值都是true
,所以我们只使用&
的结果作为条件。
您也可以移动值并与1
进行比较,但以另一种方式进行比较的好处是,掩码通常可以在编译过程中预先计算,因此检查在运行时变成了一个简单的二进制and。
如今,使用std::bitset
:这样做更为整洁
// Replace 4 with the number of meaningful bits
// N.B. index is still 0-based. 1 means the second bit.
if(std::bitset<4>(value).test(2)) {
// the bit is set
}
else {
//the bit is not set
}
这取决于"第三位";是从左起或从右起的第三位。在任何一种情况下,我都将使用比特移位(>>
运算符(来移动"0";第三位";到第一个位置,然后对CCD_ 11使用and(&
运算符(。如果设置了该位,AND将返回1,如果未设置该位,则AND将返回0。
在伪代码中:
x = 0b1011101
^ counting this one as the third bit
x = x >> 2 (x is now 0b10111)
is_third_bit_set = x & 1
并将返回1
,作为:
10111
& 00001
-------
00001