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).
+6
A:
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
2010-10-08 21:12:56
How do you calculate that the 5th flag is 0x10?
Ron Gejman
2010-10-08 21:14:59
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
2010-10-08 21:18:53
Oh, obviously. Thanks!
Ron Gejman
2010-10-08 21:19:47
+1
A:
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 ) { .. }
ArunSaha
2010-10-08 21:48:47