C++: I have a string representing 8 bits. How Do I convert it to a char?
ie. "11111111" should convert to 0b11111111 / 255 (in de开发者_JAVA技巧c)
Try strtol
with a base of 2.
Another possibility would be value = std::bitset<8>("11111111").to_ulong()
. This is more specialized for binary than strtol
, so it could provide advantages if you might want to manipulate some bits. E.g., if you wanted to read a number, flip bit 5, and then convert.
You say specifically 8 bits, so:
static_cast<char>(std::bitset<8>(str).to_ulong());
精彩评论