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).
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
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 ) { .. }
精彩评论