#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    2
    Rep Power
    0

    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. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    What's the endian-ness of your computer? Little-endian or big-endian? Just as a wild guess, is your computer an Intel box? Then it would be little-endian.

    In a big-endian platform (most significant byte first), 08 00 would be 0x0800.
    In a little-endian platform (least significant byte first), 08 00 would be 0x0008.
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    2
    Rep Power
    0
    @dwise1_aol, I'll check if it's an endian problem. Thanks for the suggestion.

    @salem, I appreciate your suggestion on the C Board, but I'm confused about the concept of cross-posting. Isn't this a completely different (and hence, unrelated) board to C Board? I could understand how it's cross-posting if I posted the same question on different sub-forums on the same board, but that wasn't the case here. I assumed that in most cases, different people would typically visit different boards, just like how I don't visit every C programming forum out there. So is cross-posting simply posting the same thing on different forums? :confused: That just seems very restrictive to me.

IMN logo majestic logo threadwatch logo seochat tools logo