简体   繁体   中英

C++ int to string as binary

The int 4112 in binary is 0001 0000 0001 0000.

How can I write it into a C++ string in binary format?

...so that when the string is hex dumped it reads:

01 00 01 00

...rather than the ascii:

31 30 31 30

I have tried using stringstream but maybe there is another way.

Thanks,

Rog

Here's just two ways to output in binary and in hex

#include <iostream>
#include <bitset>

int main()
{
    std::bitset<16> bits{ 4112 };

    // this is binary output
    std::cout << bits.to_string() << "\n";

    // this is hex output
    std::cout << std::hex << 4112;

    return 0;
}

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