Search code examples
c++bit-manipulationbitset

How to check the value of a bit in C++


I would like to check the value of the 5th and the 4th bit starting from the left in this strings like this one:

value: "00001101100000000000000001000110"

value: "00000101100000000000000001000110" 

value: "00010101100000000000000001000110"

The value is generated as a string in this way:

        msg.value = bitset<32>(packet.status()).to_string();

to be sent a a ROS node and I receive it as a string. Can I still use bitset to check the value of the bits even if it is a string? What is the best solution to check them?


Solution

  • You don't have a bitset, you have a string, in which each "bit" is represented by a char.

    To check the 4th and 5th "bits", just use:

    1. msg.value[3] != '0' and msg.value[4] != '0'

    2. msg.value[3] & 1 and msg.value[4] & 1

    #2 might be faster; it exploits the fact that '0' and '1' differ in the lowest bit only.