0

I am trying to parse some files that have a bitwise flag column. There are 11 bits in this flag and I need to find out, for each row in the files, what is the value of the 5th bit (1-based).

Ron Gejman
  • 6,135
  • 3
  • 25
  • 34

2 Answers2

6
if (flags & 0x10) ....

how did I know that mask (0x10)

here are 8 bits

0b00000000

here is the fifth one starting from one (from the right)

  87654321        
0b00010000

and in hex that is

0x10
pm100
  • 48,078
  • 23
  • 82
  • 145
  • How do you calculate that the 5th flag is 0x10? – Ron Gejman Oct 08 '10 at 21:14
  • 1
    Because the bits are powers of two: 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80. Just a fundamental property of the binary number system, each bit is twice the value of the previous one. – Ben Voigt Oct 08 '10 at 21:18
1

May be overkill for small number of flags, but I find easier to manipulate bits using std::bitset.

First, "construct" a bitset of 11 bits from the flags.

std::bitset< 11 > flags_bitset( flags );

Then, "test" the fifth bit

if( flags_bitset.test( 4 ) {  // 4, because indexing is 0 based.
    /* something */
}

See: http://www.cplusplus.com/reference/stl/bitset/test/

For doing by hand, try

const uint32_t mask = 1U << 4;  // '1' in fifth bit and rest '0' 
if( flag & mask ) { .. }
Arun
  • 19,750
  • 10
  • 51
  • 60