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?
CodePudding user response:
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:
msg.value[3] != '0'
andmsg.value[4] != '0'
msg.value[3] & 1
andmsg.value[4] & 1
#2 might be faster; it exploits the fact that '0'
and '1'
differ in the lowest bit only.
CodePudding user response:
Just create the bitset on its own, do the tests and then make a string out of it. (Or recreate a bitset from the string and test on that)
#include <bitset>
#include <string>
#include <iostream>
struct msg_t
{
std::string value;
};
struct packet_t
{
std::string status()
{
return "00001101100000000000000001000110";
}
};
int main()
{
packet_t packet;
auto bits = std::bitset<32>(packet.status());
bool bit4 = bits.test(4);
bool bit5 = bits.test(5);
if (bit4) std::cout << "bit 4 is set\n";
if (bit5) std::cout << "bit 5 is set\n";
msg_t msg;
msg.value = bits.to_string();
return 0;
}