如何打印(使用 cout)二进制形式的数字?

我正在学习关于操作系统的大学课程,我们正在学习如何从二进制转换为十六进制、从十进制转换为十六进制等.今天我们刚刚学习了如何使用二进制补码将有符号/无符号数字存储在内存中(~数字 + 1).

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

我们需要在纸上做一些练习,我希望能够在将作业提交给老师之前验证我的答案.我为前几个练习编写了一个 C++ 程序,但现在我不知道如何用以下问题验证我的答案:

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;

我们需要显示abc的二进制表示在内存中.

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(它是一个字符,所以 1 个字节)

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

b = 00001000(它是一个字符,所以 1 个字节)

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

c = 11111110 11000101(很短,所以2个字节)

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

有没有办法验证我的答案?C++ 中是否有标准方法来显示数字内存中的二进制表示,还是我必须自己编写每个步骤(计算二进制补码然后转换为二进制)?我知道后者不会花这么长时间,但我很好奇是否有标准的方法来做到这一点.

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.

推荐答案

最简单的方法可能是创建一个 std::bitset 表示该值,然后将其流式传输到 cout.

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 << '
';

相关文章