C++:了解我的计算机如何存储字节

C++: Finding out how my computer stores bytes

本文关键字:存储 字节 何存储 了解 我的 计算机 C++      更新时间:2023-10-16

得到了这个作业,我们将检查我们的计算机如何存储字节等等,我无法真正掌握如何获得正确答案,但代码几乎解释了我的想法。

提前谢谢。

#include <iostream>
using namespace std;
union hexNumber{
      signed short normal;
      signed short twoByte1, twoByte2;
      signed short fourByte1, fourByte2, fourByte3, fourByte4;
} theNumber;
int main()
{
    int number;
    cout << "Write your number (int): " << endl;
    cin >> number;
    theNumber.normal = number;
    cout << "nNormal: " <<std::hex << theNumber.normal << endl;
    theNumber.twoByte1 = number;
    theNumber.twoByte2 = number;
    (theNumber.twoByte1 & 0x00001111);
    (theNumber.twoByte2 & 0x11110000);
    cout << "nTwoByte1: " <<std::hex << theNumber.twoByte1 << endl;
    cout << "TwoByte2: " <<std::hex << theNumber.twoByte2 << endl;
    theNumber.fourByte1 = number; 
    theNumber.fourByte2 = number;
    theNumber.fourByte3 = number;
    theNumber.fourByte4 = number;
    (theNumber.fourByte1 & 0x00000011);
    (theNumber.fourByte2 & 0x00001100);
    (theNumber.fourByte3 & 0x00110000);
    (theNumber.fourByte4 & 0x11000000);
    cout << "nfourByte1: " << std::hex << theNumber.fourByte1 << endl;
    cout << "fourByte2: " << std::hex << theNumber.fourByte2 << endl;
    cout << "fourByte3: " << std::hex << theNumber.fourByte3 << endl;
    cout << "fourByte4: " << std::hex << theNumber.fourByte4 << endl;
    system("pause");
}

它们都打印相同的东西。

它们打印都是一样的,因为你在联合中只使用short。你可能想写的是:

union HexNumber {
  int full_number; // assuming 'int' is 4-bytes; int32_t would be 
  unsigned char b[4]; // uint8_t would be better
} theNumber;
theNumber.full_number = number;
std::cout << std::hex << (int)theNumber.b[0] << " " << (int)theNumber.b[1] 
    << " " << (int)theNumber.b[2] << " " << (int)theNumber.b[3] << std::endl;

你似乎真正想要的是:

union hexNumber{
      int fourBytes;
      short twoBytes[2];
      char oneByte[4];
} theNumber;

现在,hexNumber对象可以被视为int,2 short的数组或4 char的数组。

但请注意,intshortchar的大小是实现定义的。更跨平台的版本是:

union hexNumber{
      std::int32_t fourBytes;
      std::int16_t twoBytes[2];
      std::int8_t oneByte[4];
} theNumber;

这些类型可从<cstdint>标头获得。

这些行:(theNumber.fourByte1 & 0x00000011);他们什么都不做。结果不会存储在任何地方。你的意思是

theNumber.fourByte1 = (theNumber.fourByte1 & 0x00000011);

联合中应该有不同的数据类型,此外,您应该添加一个长度为零的位字段。

std::int32_t force_align : 0 ;

确保对齐。