C++:找出我的计算机如何存储字节

Dan*_*boy 0 c++ signed byte short endianness

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

提前致谢.

#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");
}
Run Code Online (Sandbox Code Playgroud)

他们都打印相同的东西.

nul*_*ptr 5

他们打印所有相同,因为你只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;
Run Code Online (Sandbox Code Playgroud)