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).
Asked
Active
Viewed 1,062 times
0
-
You need to provide more information. How are the bits encoded into this file? Is it ASCII hex? Raw binary? – Amardeep AC9MF Oct 08 '10 at 21:13
-
ASCII. The bits are encoded as a number (e.g., the first 3 rows have: 0, 4 and 16). – Ron Gejman Oct 08 '10 at 21:14
-
possible duplicate of [How to check my byte flag?](http://stackoverflow.com/questions/127027/how-to-check-my-byte-flag) – Kristopher Johnson Oct 08 '10 at 21:32
2 Answers
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
-
-
1Because 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