c++ - 如何找到数字的第三位
问题描述
我对 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++ 中有更简洁的方法可以做到这一点,仍然值得至少能够在它弹出时识别出老派模式:
// 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 << 3
是0b00001000
一个 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
}
推荐阅读
- c# - 在使用 Fody Costura 和 Topshelf 和 Ninject 的特定机器上缺少参考
- java - QueryDsl SQL - 左连接子查询
- python-3.x - 使用 pyinstaller 编译代码时 Python exec() 不起作用
- c# - 当有更多值时如何从字典中获取值
- python - 在后台为 GUI 运行函数
- r - 如何使用 ggplot2 stat_smooth 绘制具有随机效应的 glmer 模型?
- ruby - 如何在当前 shell 的上下文中执行 Ruby 系统调用
- python - if 语句中的多个条件在使用字符串时不起作用
- azure-ad-b2c - Azure B2C 不适用于本机客户端应用程序
- spring-boot - 如何在 application.yml 中指定 logback 滚动附加程序?