本文介绍了C ++ - 如何打印(使用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).

我们有几个exercices做在纸上,我希望能够提交我的作品交给老师之前确认我的答案。我写了一个C ++程序前几exercices但现在我卡住了,我怎么能验证我有以下问题的答案:

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;

和我们需要显示二进制重新presentation的 A B 的C $ C>和 C

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

我已经做到了在纸面上,这让我的结果如下(在数字存储器中的所有二进制重新presentations二进制补码后):

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个字节)

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 ++标准的方式来显示在多个存储二进制重新presentation,或者我有code每一步我自己(计算补,然后转换为二进制)?我知道后也不会这么长的时间,但我很好奇,如果有这样做的标准方式。

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

另外,我真的不知道该标签挑来随时相应地改变它们。

推荐答案

最简单的方法可能是创建的重新presenting值,则流,为 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;

这篇关于C ++ - 如何打印(使用COUT)一个号码存储在内存中的方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 07:34
查看更多