C/C++ check if one bit is set in, i.e. int variable

int temp = 0x5E; // in binary 0b1011110.

Is there such a way to check if bit 3 in temp is 1 or 0 without bit shifting and masking.

Just want to know if there is some built in function for this, or am I forced to write one myself.

342926 次浏览

检查是否设置了位 N (从0开始) :

temp & (1 << N)

没有内置的功能。

在 C 语言中,如果你想隐藏位操作,你可以编写一个宏:

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

并用这种方式从右端检查 n这个位:

CHECK_BIT(temp, n - 1)

In C++, you can use 位集.

您可以“模拟”移位和屏蔽: 如果((0x5e/(2 * 2 * 2))% 2) ..。

有,即 一点点内部指令。

根据 位字段的这种描述,有一种直接定义和访问字段的方法:

struct preferences {
unsigned int likes_ice_cream : 1;
unsigned int plays_golf : 1;
unsigned int watches_tv : 1;
unsigned int reads_books : 1;
};


struct preferences fred;


fred.likes_ice_cream = 1;
fred.plays_golf = 1;
fred.watches_tv = 1;
fred.reads_books = 0;


if (fred.likes_ice_cream == 1)
/* ... */

Also, there is a warning there:

However, bit members in structs have practical drawbacks. First, the ordering of bits in memory is architecture dependent and memory padding rules varies from compiler to compiler. In addition, many popular compilers generate inefficient code for reading and writing bit members, and there are potentially severe thread safety issues relating to bit fields (especially on multiprocessor systems) due to the fact that most machines cannot manipulate arbitrary sets of bits in memory, but must instead load and store whole words.

如果你只是想要一个真正的硬编码方式:

 #define IS_BIT3_SET(var) ( ((var) & 0x04) == 0x04 )

请注意这是如何依赖的,并假设这个位顺序为76543210,var 为8位。

#include "stdafx.h"
#define IS_BIT3_SET(var) ( ((var) & 0x04) == 0x04 )
int _tmain(int argc, _TCHAR* argv[])
{
int temp =0x5E;
printf(" %d \n", IS_BIT3_SET(temp));
temp = 0x00;
printf(" %d \n", IS_BIT3_SET(temp));
temp = 0x04;
printf(" %d \n", IS_BIT3_SET(temp));
temp = 0xfb;
printf(" %d \n", IS_BIT3_SET(temp));
scanf("waitng %d",&temp);


return 0;
}

结果:

1 0 1 0

是的,我知道我不会这样做,但是我通常会写:

    /* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }


template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }

例如:

IsBitSet( foo, BIT(3) | BIT(6) );  // Checks if Bit 3 OR 6 is set.

除了其他方面,这种方法还包括:

  • 容纳8/16/32/64位整数。
  • 在我不知道和不同意的情况下检测 IsBitSet (int32,int64)调用。
  • 内联模板,因此没有函数调用开销。
  • Const & 引用,因此没有需要复制/复制的 needs。我们可以保证编译器会检测到任何试图更改参数的输入错误。
  • 0!使代码更加清晰明了。编写代码的主要目的总是清晰有效地与其他程序员交流,包括那些技能较低的程序员。
  • 虽然不适用于这种特殊情况... 一般来说,模板化函数可以避免多次计算参数的问题。一些 # Definition 宏的已知问题。< br > 例如: # 定义 ABS (X)((X) < 0) ?- (X) : (X)) < br > ABS (i + +) ;

如果是 C + + ,我会直接使用 std: : 位集。简单。直接。不会出现愚蠢的错误。

typedef std::bitset<sizeof(int)> IntBits;
bool is_set = IntBits(value).test(position);

or how about this silliness

template<unsigned int Exp>
struct pow_2 {
static const unsigned int value = 2 * pow_2<Exp-1>::value;
};


template<>
struct pow_2<0> {
static const unsigned int value = 1;
};


template<unsigned int Pos>
bool is_bit_set(unsigned int value)
{
return (value & pow_2<Pos>::value) != 0;
}


bool result = is_bit_set<2>(value);

Use std::bitset

#include <bitset>
#include <iostream>


int main()
{
int temp = 0x5E;
std::bitset<sizeof(int)*CHAR_BITS>   bits(temp);


// 0 -> bit 1
// 2 -> bit 3
std::cout << bits[2] << std::endl;
}

For the low-level x86 specific solution use the x86 测试 opcode.

你的编译器应该把 一点点变成这样..。

最快的方法似乎是找到面具

我尝试读取一个32位整数,它定义了 PDF 文件中对象的标志,但这对我没用

what fixed it was changing the define:

#define CHECK_BIT(var,pos) ((var & (1 << pos)) == (1 << pos))

操作数 & 返回一个带有标志的整数,这两个标志都在1中,并且它没有正确地转换为布尔值,这就解决了问题

While it is quite late to answer now, there is a simple way one could find if Nth bit is set or not, simply using POWER and MODULUS mathematical operators.

Let us say we want to know if 'temp' has Nth bit set or not. The following boolean expression will give true if bit is set, 0 otherwise.

  • (温度模2 ^ N + 1 > = 2 ^ N)

考虑下面的例子:

  • Int temp = 0x5E;//在二进制文件0b1011110//BIT 0中是 LSB

如果我想知道第三位是否设置,我得到

  • (94 MODULUS 16) = 14 > 2^3

表达式返回 true,表示设置了第3位。

为什么不用这么简单的东西呢?

uint8_t status = 255;
cout << "binary: ";


for (int i=((sizeof(status)*8)-1); i>-1; i--)
{
if ((status & (1 << i)))
{
cout << "1";
}
else
{
cout << "0";
}
}

输出: 二进制: 11111111

所选择的答案实际上是错误的。下面的函数将返回位位置或0,具体取决于是否实际启用了位。这不是海报要求的。

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

Here is what the poster was originally looking for. The below function will return either a 1 or 0 if the bit is enabled and not the position.

#define CHECK_BIT(var,pos) (((var)>>(pos)) & 1)

一种方法是在以下条件下进行检查:

if ( (mask >> bit ) & 1)

解说节目包括:

#include <stdio.h>


unsigned int bitCheck(unsigned int mask, int pin);


int main(void){
unsigned int mask = 6;  // 6 = 0110
int pin0 = 0;
int pin1 = 1;
int pin2 = 2;
int pin3 = 3;
unsigned int bit0= bitCheck( mask, pin0);
unsigned int bit1= bitCheck( mask, pin1);
unsigned int bit2= bitCheck( mask, pin2);
unsigned int bit3= bitCheck( mask, pin3);


printf("Mask = %d ==>>  0110\n", mask);


if ( bit0 == 1 ){
printf("Pin %d is Set\n", pin0);
}else{
printf("Pin %d is not Set\n", pin0);
}


if ( bit1 == 1 ){
printf("Pin %d is Set\n", pin1);
}else{
printf("Pin %d is not Set\n", pin1);
}


if ( bit2 == 1 ){
printf("Pin %d is Set\n", pin2);
}else{
printf("Pin %d is not Set\n", pin2);
}


if ( bit3 == 1 ){
printf("Pin %d is Set\n", pin3);
}else{
printf("Pin %d is not Set\n", pin3);
}
}


unsigned int bitCheck(unsigned int mask, int bit){
if ( (mask >> bit ) & 1){
return 1;
}else{
return 0;
}
}

产出:

Mask = 6 ==>>  0110
Pin 0 is not Set
Pin 1 is Set
Pin 2 is Set
Pin 3 is not Set

我用这个:

#define CHECK_BIT(var,pos) ( (((var) & (pos)) > 0 ) ? (1) : (0) )

其中“ pos”定义为2 ^ n (如1,2,4,8,16,32...)

返回: 1 if true 如果为假,则为0

我做了这个:

LatGbits.latG0 = ((m & 0x8) > 0) ;//检查 m 的 bit-2是否为1

#define CHECK_BIT(var,pos) ((var>>pos) & 1)

pos - Bit position strarting from 0.

返回0或1。

为什么所有这些位移操作都需要库函数?如果你有 OP 发布的值: 1011110,并且你想知道从右边第三个位置的位是否被设置,只需要做:

int temp = 0b1011110;
if( temp & 4 )   /* or (temp & 0b0100) if that's how you roll */
DoSomething();

或者一些更漂亮的东西,可能更容易被未来的代码读者理解:

#include <stdbool.h>
int temp = 0b1011110;
bool bThirdBitIsSet = (temp & 4) ? true : false;
if( bThirdBitIsSet )
DoSomething();

或者,不需要 # include:

int temp = 0b1011110;
_Bool bThirdBitIsSet = (temp & 4) ? 1 : 0;
if( bThirdBitIsSet )
DoSomething();

先前的答案向您展示了如何处理位检查,但是通常情况下,它完全是关于编码在一个整数中的标志,这在以前的任何情况下都没有得到很好的定义。

在一个典型的场景中,标志本身被定义为整数,对于它所引用的特定位,位数为1。在下面的示例中,您可以检查整数是否有来自标志列表(连接了多个错误标志)的 ANY 标志,或者是否每个标志都在整数中(连接了多个成功标志)。

以下示例说明如何处理整数中的标志。

这里有一个实例: Https://rextester.com/xike82408

//g++  7.4.0


#include <iostream>
#include <stdint.h>


inline bool any_flag_present(unsigned int value, unsigned int flags) {
return bool(value & flags);
}


inline bool all_flags_present(unsigned int value, unsigned int flags) {
return (value & flags) == flags;
}


enum: unsigned int {
ERROR_1 = 1U,
ERROR_2 = 2U, // or 0b10
ERROR_3 = 4U, // or 0b100
SUCCESS_1 = 8U,
SUCCESS_2 = 16U,
OTHER_FLAG = 32U,
};


int main(void)
{
unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
    

std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
return 0;
}

最快最好的宏观经济

#define get_bit_status()    ( YOUR_VAR  &   ( 1 << BITX ) )


.
.


if (get_rx_pin_status() == ( 1 << BITX ))
{
do();
}