Access to the last 2 bytes of an integer

I have a structure that contains an integer and char .. how can I access the last 2 bytes of my int

+3
source share
6 answers

The term "last byte" in an integer expression is not clear. There are two things you might think about:

  • Largest / smallest significant bytes .
  • Last bytes when the integer is encoded in either small or large endian form . Endianness is often called byte order.

In the first case, the least significant bytes can be accessed in most languages ​​using (x and 0xffff).

, . , , . , .

+10
int i = // ?? get your int somehow
int lastTwoBytes = i & 0x0000FFFF;
int firstTwoBytes = (i >> 16) & 0x0000FFFF; // maybe you really want the first two?
+5

:

union {
    int           i;
    unsigned char bytes[sizeof(int)];
} int_bytes;

, .

+4

, C/++, - :

struct {
  int myInt;
  char myChar;
} myStruct;

:

lastTwoBytesOfInt = myStruct.myInt & 0x0000FFFF;

Wikipedia, , .

, Endianness, "" .

+2

Here's another way to access the upper and lower 16-bits (assuming the short is 16 bits on your system):

unsigned int x = 0x12345678;
cout << hex << ((unsigned short*)&x)[0] << endl; // prints 5678
cout << hex << ((unsigned short*)&x)[1] << endl; // prints 1234

Please note that the result depends on the suitability of your system. http://en.wikipedia.org/wiki/Endianness

+1
source

In windows, you can use HiWord () / LoWord () to access the first or last 2 bytes.

0
source

Source: https://habr.com/ru/post/1756065/


All Articles