开发者

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

开发者 https://www.devze.com 2023-02-18 22:32 出处:网络
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

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());

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号