Search code examples
c++byteendiannesssignedshort

C++: Finding out how my computer stores bytes


Got this assignment where we are going to check how our computers store bytes and so on and I can't really grasp how to get the correct answer, but the code pretty much explains how I am thinking.

Thanks in advance.

#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");
}

They all print the same things.


Solution

  • They print all the same because you use only short in your union. What you might want to write instead would be:

    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;