1. ## Reading a “short” variable into a structure

Hi,

I have a sequence of 4 bytes that I wish to read into a structure.

The structure definition is

Code:
```struct A
{
u_char Char1;
u_char Char2;
u_short Short3;
}```
Then I wish to compare A.Short3 with a 2-byte value, i.e.

Code:
```#define Match 0x0800
struct A *H;
u_char *p;  // points to a sequence of bytes 12 34 08 00

H = (struct A *)(p);
if (H->Short3 == Match)
...```
However, I seem to be unable to read the 3rd and 4th byte as a short variable. I printed out the hex value of H->Short3 and Match, and got 8 and 800 respectively. It seems like H->Short3 only got the byte 0x08 instead of both bytes 0x0800.

How do I read 0x0800 into H->Short3?

Thank you!

2. How are you attempting to read the short variable? What data are you reading by your method?

Without those bits of information, there is no way to answer your question.

My guess is that you have a padding problem - for performance reasons, compilers often add padding between struct members. Your code is assuming there is no such padding.

3. 1. Verify that sizeof(struct A) is indeed 4

2. Verify that this gives you the same result.
Code:
```struct A H;
u_char *p;  // points to a sequence of bytes 12 34 08 00
memcpy(&H,p,sizeof(H));
if (H.Short3 == Match)```
If p is a mis-aligned address, then dereferencing members with alignment requirements can produce weird effects.

3. Verify the endian of your machine.
Code:
```struct A H;
H.Char1 = 0x12;
H.Char2 = 0x34;
H.Short3 = Match;
unsigned char *p = (unsigned char *)&H;
for ( i = 0 ; i < 4 ; i++ ) printf("%02x ", p[i]);```
If your machine is opposite endian to your data stream, then you'll see
12 34 00 08

4. It looks like order problem

I would read 2 bytes into short using code:
Code:
```H->Short3 = (u_short)high;
H->Short3 <<= 8;
H->Short3 |= (u_short)low;```
looks like in your method the values of high and low are swapped

5. Thank you all for the suggestions, I'll try them out and get back with the results. BTW, the sequence of bytes I'm reading from is from a pcap handle, i.e. I'm reading packet data.

6. so the byte order is defined by rfc describing corresponding header you are reading - use it.

7. Thanks to everybody for your suggestions. It was indeed an endian issue and after correcting for it, I'm able to read the bytes in the correct order.