127
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.

22 Answers 22

191

In C, if you want to hide bit manipulation, you can write a macro:

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

and use it this way to check the nth bit from the right end:

CHECK_BIT(temp, n - 1)

In C++, you can use std::bitset.

9
  • 3
    In case you need a simple truth value, it should be !!((var) & (1 << (pos))). Feb 7, 2009 at 13:27
  • 11
    @Eduard: in C, everything != 0 is true, so why bother? 1 is exactly as true as 0.1415!
    – Christoph
    Feb 7, 2009 at 13:39
  • 1
    And in case you're using C++, you could (should) write a template instead of a macro. :)
    – jalf
    Feb 7, 2009 at 14:45
  • 3
    In C this is fine. But this kind of macros in C++. That's horrible and so open to abuse. Use std::bitset Feb 7, 2009 at 16:25
  • 2
    @Christoph You will find out when someone does something like 'typedef char BOOL' and you try to pass the output of CHECK_BIT as a BOOL argument that happens to check a bit past the 8th one. It is a seriously tricky bug to track down and caused at least one massive security breach. always flatten your bools. (or use stdbool.h) Jan 13, 2015 at 8:03
109

Check if bit N (starting from 0) is set:

temp & (1 << N)

There is no builtin function for this.

3
  • 21
    +1 for mentioning it's starting from 0 since I suspect the OP was thinking 1-based and the accepted answer will get him into trouble. :)
    – Jim Buck
    Feb 7, 2009 at 17:36
  • Hm. Why is this starting from 0? What do we get when 1 << 0?? Sorry, confused.
    – Danijel
    Feb 1, 2016 at 14:59
  • 7
    OK, got it. We start from 0th possition, which is 1<<0, which is 1 without any shift (shift 0), which is 1<<0 == 1
    – Danijel
    Feb 1, 2016 at 15:00
32

I would just use a std::bitset if it's C++. Simple. Straight-forward. No chance for stupid errors.

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);
3
  • 7
    @user21714 I guess u meant std::bitset<8 * sizeof(int)>
    – iNFINITEi
    Jun 7, 2016 at 12:58
  • 1
    or std::numeric_limits<int>::digits
    – Léo Lam
    Aug 19, 2017 at 13:10
  • 2
    @iNFINITEi std::bitset<CHAR_BIT * sizeof(int)> to be even more correct
    – Xeverous
    Apr 23, 2018 at 9:24
23

What the selected answer is doing is actually wrong. The below function will return the bit position or 0 depending on if the bit is actually enabled. This is not what the poster was asking for.

#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)
3
  • 2
    It took some time until I understood what you mean. More exact: The first function returns 2 to the power of the bit position if the bit is set, 0 otherwise.
    – lukasl1991
    Apr 29, 2019 at 9:16
  • 2
    This is the exact issue I just encountered while using it like bool has_feature = CHECK_BIT(register, 25); Good to know I could do it without the double-negate.
    – Jimmio92
    Aug 30, 2019 at 18:01
  • The double negate might be "costly", but if pos is a constant (as it usually is), the advantage is that the compiler can replace 1 << (4) with 0b10000. Not sure if that shifting or the double negate is cheaper. Aug 10, 2021 at 19:51
14

Yeah, I know I don't "have" to do it this way. But I usually write:

    /* 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); }

E.g.:

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

Amongst other things, this approach:

  • Accommodates 8/16/32/64 bit integers.
  • Detects IsBitSet(int32,int64) calls without my knowledge & consent.
  • Inlined Template, so no function calling overhead.
  • const& references, so nothing needs to be duplicated/copied. And we are guaranteed that the compiler will pick up any typo's that attempt to change the arguments.
  • 0!= makes the code more clear & obvious. The primary point to writing code is always to communicate clearly and efficiently with other programmers, including those of lesser skill.
  • While not applicable to this particular case... In general, templated functions avoid the issue of evaluating arguments multiple times. A known problem with some #define macros.
    E.g.: #define ABS(X) (((X)<0) ? - (X) : (X))
          ABS(i++);
10

According to this description of bit-fields, there is a method for defining and accessing fields directly. The example in this entry goes:

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.

7

You can use a Bitset - http://www.cppreference.com/wiki/stl/bitset/start.

0
5

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;
}
4
  • 1
    A couple of things worth mentioning here - bits[3] will give you the 4th bit - counting from the LSB to MSB. To put it loosely, it will give you the 4the bit counting from right to left. Also, sizeof(int) gives the number of characters in an int, so it would need to be std::bitset<sizeof(int)*CHAR_BITS> bits(temp), and bits[sizeof(int)*CHAR_BITS - 3] to test the 3rd bit counting from MSB to LSB, which is probably the intent. Nov 4, 2009 at 19:27
  • 2
    Yes, but I think the questioner (and people coming from google searches) might not have that skill, and your answer could mislead them. Nov 5, 2009 at 16:07
  • This answer is terrible. It should be deleted.
    – Adam Burry
    Nov 1, 2013 at 3:02
  • Doesn't the value temp need to be reflected to make it "big-endian"?
    – jww
    Apr 9, 2018 at 4:33
5
#define CHECK_BIT(var,pos) ((var>>pos) & 1)

pos - Bit position strarting from 0.

returns 0 or 1.

4

i was trying to read a 32-bit integer which defined the flags for an object in PDFs and this wasn't working for me

what fixed it was changing the define:

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

the operand & returns an integer with the flags that both have in 1, and it wasn't casting properly into boolean, this did the trick

1
  • != 0 would do the same. Do not know how the generated machine instructions might differ.
    – Adam Burry
    Nov 1, 2013 at 3:07
4

I use this:

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

where "pos" is defined as 2^n (i.g. 1,2,4,8,16,32 ...)

Returns: 1 if true 0 if false

1
  • 2
    I think this is the only correct answer for both C and C++. It is the only one that respects the "... without bit shifting and masking" requirement. You should probably explicitly state to use 4 = 2^(3-1) for bit position 3 since it was part of the question.
    – jww
    Apr 9, 2018 at 4:37
3

There is, namely the _bittest intrinsic instruction.

7
  • 4
    The link indicates "Microsoft Specific". Use it only if you don't need your code to be portable.
    – mouviciel
    Feb 7, 2009 at 13:25
  • The link indicates "Microsoft Specific", but it's an intrinsic taken over from the Intel C++ compiler, and it results in a BT instruction, so you can do it with inline assembler too. Of course, that doesn't make it more portable. Feb 7, 2009 at 13:44
  • 1
    It's also specific to the x86 architecture. So no, definitely not portable.
    – jalf
    Feb 7, 2009 at 14:46
  • I'm sure other architectures have similar options. Feb 7, 2009 at 16:28
  • The very point of intrinsics is that they take advantage of hardware if it exists, and use a software replacement if the hardware does not handle it.
    – Eclipse
    Feb 7, 2009 at 18:39
3

The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.

In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).

Following an example of how to handle flags in an integer.

Live example available here: 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;
}
2

For the low-level x86 specific solution use the x86 TEST opcode.

Your compiler should turn _bittest into this though...

1
  • I would prefer BT over TEST as BT fits the task in a better way.
    – u_Ltd.
    May 14, 2015 at 10:47
2

Why all these bit shifting operations and need for library functions? If you have the value the OP posted: 1011110 and you want to know if the bit in the 3rd position from the right is set, just do:

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

Or something a bit prettier that may be more easily interpreted by future readers of the code:

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

Or, with no #include needed:

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

You could "simulate" shifting and masking: if((0x5e/(2*2*2))%2) ...

4
  • 1
    We could sort a list by randomly shuffling it and testing to see if it's now "sorted". E.g.: while( /*NOT*/! isSorted() ) { RandomlyShuffle(); } But we don't...
    – Mr.Ree
    Feb 7, 2009 at 16:21
  • This solution is extremely wasteful on resources and unintuitive. divs, muls and mods are the three most expensive functions. by comparision tests, ands and shifts are among the cheapest - some of the few you might actually get done in less than 5 cycles.
    – jheriko
    Feb 9, 2009 at 16:38
  • That might be (and is not, because modern processors detest bits and jumps). The OP originally asked explicitly for a solution "without bit shifting and masking." So go on and give more negative points for a matching but slow answer. I won't delete the post just because the OP changed his mind.
    – Leonidas
    Feb 9, 2009 at 17:03
  • It looks tricky. Let's not vote down this answer. Sometimes it's good to explore other views.
    – Viet
    Nov 23, 2010 at 10:44
1

One approach will be checking within the following condition:

if ( (mask >> bit ) & 1)

An explanation program will be:

#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;
   }
}

Output:

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

if you just want a real hard coded way:

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

note this hw dependent and assumes this bit order 7654 3210 and var is 8 bit.

#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;
}

Results in:

1 0 1 0

3
  • 1
    The & operation is done on values not on the internal representation.
    – Remo.D
    Feb 7, 2009 at 17:43
  • Hi Remo.D -- Not sure I understand your comment? I have include some 'c' code that works just fine.
    – simon
    Feb 7, 2009 at 18:25
  • 1
    His point is that it's not hardware-dependant - IS_BIT3_SET will always test the 4th least significant bit
    – Eclipse
    Feb 7, 2009 at 18:43
0

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.

  • ( temp MODULUS 2^N+1 >= 2^N )

Consider the following example:

  • int temp = 0x5E; // in binary 0b1011110 // BIT 0 is LSB

If I want to know if 3rd bit is set or not, I get

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

So expression returns true, indicating 3rd bit is set.

0

Why not use something as simple as this?

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";
  }
}

OUTPUT: binary: 11111111

1
  • if else can be done easily with a ternary: std::cout << (((status & (1 << i)) ? '1' : '0');. You should use the CHAR_BIT constant from <climits> instead of hard coding 8 bits, though in this case you know the result will be 8 anyway since you are using a uint8_t Aug 6, 2015 at 18:59
-1

I make this:

LATGbits.LATG0=((m&0x8)>0); //to check if bit-2 of m is 1

-3

the fastest way seems to be a lookup table for masks

Not the answer you're looking for? Browse other questions tagged or ask your own question.