C ++: узнать, как мой компьютер хранит байты

0

Получил это задание, где мы собираемся проверить, как наши компьютеры хранят байты и т.д., И я не могу понять, как получить правильный ответ, но код в значительной степени объясняет, как я думаю.

Заранее спасибо.

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

Все они печатают одни и те же вещи.

  • 0
    Почему эти побитовые операции там?
  • 0
    Вы можете заметить, что short обычно адресует два байта, а не один. Если вы хотите сослаться на один байт, используйте unsigned char или std::uint8_t из <cstdint> .
Теги:
endianness
signed
byte
short

4 ответа

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;
  • 1
    Разве theNumber.b1 , b2 , b3 и b4 иметь доступ к одной и той же вещи? Неважно, что они на одной линии. Они должны быть внутри агрегатного типа (например, struct или массив).
  • 0
    К сожалению. Конечно, они будут. Спасибо! Я исправлю ответ.
3

То, что вы действительно хотите, это что-то вроде:

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

Теперь объект hexNumber можно рассматривать как либо int, массив из двух short s, либо массив из 4 char s.

Обратите внимание, однако, что размеры int, short и char определены реализацией. Более кросс-платформенная версия будет:

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

Эти типы доступны из заголовка <cstdint>.

0

У вас должен быть другой тип данных внутри вашего союза, и вы должны добавить поле бит с нулевой длиной.

std::int32_t force_align : 0 ;

Чтобы убедиться в выравнивании.

0

Эти строки: (theNumber.fourByte1 & 0x00000011); они ничего не делают. Результат не сохраняется нигде. Ты имел ввиду

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню