如何以二进制形式打印(使用cout)数字? [英] How to print (using cout) a number in binary form?

查看:297
本文介绍了如何以二进制形式打印(使用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 << '\n';

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

这篇关于如何以二进制形式打印(使用cout)数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆