i have a struct that contains an integer and a char..how do i access the last 2 bytes of my int??
Supposing you are using C/C++, you have something like:
struct {
int myInt;
char myChar;
} myStruct;
and want this:
lastTwoBytesOfInt = myStruct.myInt & 0x0000FFFF;
Having a look at Wikipedia might help you understand bitwise operations if you don't know them yet.
Also, you might have a look at Endianness because the "last" bytes of an integer is a somewhat ambigious term.
The term "last byte" in an integer is not clear. There are two things that you might be thinking of:
- The most / least significant bytes.
- The last bytes when the integer is encoded in either little or big endian form. Endianness is often called byte order.
In the first case the least significant bytes can be accessed in most languages by using (x & 0xffff).
In the second case you will need to check what byte order you need. For example if you are using network byte order the last byte is the least significant byte. In other cases it might be the most significant byte that is the last byte.
int i = // ?? get your int somehow
int lastTwoBytes = i & 0x0000FFFF;
int firstTwoBytes = (i >> 16) & 0x0000FFFF; // maybe you really want the first two?
Using a union like this should let you get at the individual bytes of an integer:
union {
int i;
unsigned char bytes[sizeof(int)];
} int_bytes;
Exactly how many bytes compose an integer is implementation dependent.
Here's another way to access the upper and lower 16-bits (assuming 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
Note that the result depends on the endianness of your system. http://en.wikipedia.org/wiki/Endianness
On windows, you can use HiWord()/LoWord() to access the first or last 2 bytes.