首页 > 解决方案 > 如何找到数字的第三位

问题描述

我对 C++ 中的问题有疑问。我必须创建一个程序,如果第 3 位是 1,我必须从 Int 创建一个变量并在屏幕“True”上创建一个 cout<<。

我的问题是:我怎样才能看到那个数字的第三位是什么?我尝试过使用 bitset,但无法解决。请帮我。

#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++bitset

解决方案


检查是否设置了给定位是您将在许多代码库中遇到的经典模式。因此,即使在现代 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):这将创建一个蒙版。IE 一个只包含我们关心的位的值。EG1 << 30b00001000一个 8 位整数。

val & mask:这会在值和掩码之间进行二进制与,当且仅当未设置该位时,掩码将为 0。由于任何非零值都是 a true,我们只使用&as 条件的结果。

您也可以移动该值并与 进行比较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
}

推荐阅读