简体   繁体   中英

C++: how do I convert an unsigned char to a string representing the binary value that the char has?

char myChar = 0x01;

how do I get my output to be "00000001"

If there is a way to do it with a built in function, without a loop (I can do this with a loop, I just want to be elegant), that would be preferred ?

As for the why I'm doing this: I'm saving these numbers in a file that an external library needs this formatting (weird, I know, but libraries have rules).

You may use a bitset :

std::bitset<8> bits(myChar);
std::cout << bits << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM