NullVoxPopuli
NullVoxPopuli

Reputation: 65173

C++: I have a string representing 8 bits. How Do I convert it to a char?

ie. "11111111" should convert to 0b11111111 / 255 (in dec)

Upvotes: 4

Views: 383

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490378

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.

Upvotes: 10

Mark B
Mark B

Reputation: 96281

You say specifically 8 bits, so:

static_cast<char>(std::bitset<8>(str).to_ulong());

Upvotes: 4

nobody
nobody

Reputation: 20174

Try strtol with a base of 2.

Upvotes: 11

Related Questions