c++binaryiostreamrepresentationstd-bitset

How to print (using cout) a number in binary form?


I'm following a college course about operating systems and we're learning how to convert from binary to hexadecimal, decimal to hexadecimal, etc. and today we just learned how signed/unsigned numbers are stored in memory using the two's complement (~number + 1).

We have a couple of exercises to do on paper and I would like to be able to verify my answers before submitting my work to the teacher. I wrote a C++ program for the first few exercises but now I'm stuck as to how I could verify my answer with the following problem:

char a, b;

short c;
a = -58;
c = -315;

b = a >> 3;

and we need to show the binary representation in memory of a, b and c.

I've done it on paper and it gives me the following results (all the binary representations in memory of the numbers after the two's complement):

a = 00111010 (it's a char, so 1 byte)

b = 00001000 (it's a char, so 1 byte)

c = 11111110 11000101 (it's a short, so 2 bytes)

Is there a way to verify my answer? Is there a standard way in C++ to show the binary representation in memory of a number, or do I have to code each step myself (calculate the two's complement and then convert to binary)? I know the latter wouldn't take so long but I'm curious as to if there is a standard way to do so.


Solution

  • The easiest way is probably to create an std::bitset representing the value, then stream that to cout.

    #include <bitset>
    ...
    
    char a = -58;
    std::bitset<8> x(a);
    std::cout << x << '\n';
    
    short c = -315;
    std::bitset<16> y(c);
    std::cout << y << '\n';