Jesse Emond Jesse Emond - 1 month ago 17
C++ Question

C++ - How to print (using cout) the way a number is stored in memory?

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 exercices 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 exercices 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.

Thank you for your help (I couldn't find a question with a similar topic with the keywords I know so I am sorry if this is some sort of duplicate).

Also, I didn't really know which tags to pick to feel free to change them accordingly.

Answer

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;

short c = -315;
std::bitset<16> y(c);
std::cout << y;
Comments