Thread: Struct Casting

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    1

    Struct Casting

    Hi All

    I'm trying to get uint32_t data into a 4 * uint8_t struct, I dont want to pass in byte by byte so i am trying to achieve soemthing like the following:


    Code:
    uint32_t test = 0xFFFFFFFF;
    
    typedef struct word32To4xByte
    {
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
    uint8_t byte4;
    }wordtobyte;
    
    struct word32To4xByte expectedResp;
    
    ecpectedResp= (wordtobyte) test;

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You could do something like this.

    Code:
    uint32_t test = 0xFFFFFFFF;
    
    typedef struct {
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
    uint8_t byte4;
    } wordtobyte;
    
    wordtobyte expectedResp;
    
    expectedResp = *((wordtobyte*)(&test));
    Or use memcpy().

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Load in bytes, read dword... load in dword, read bytes...
    Code:
    typedef union t_dwordtobyte
    {
       uint32_t dword;
       struct bytes
        {
           uint8_t b1;
          uint8_t b2;
          uint8_t b3;
          uint8_t b4;
        }
    }dwordtobyte;
    
    
    // use as...
    dwordtobyte wb;
    
    wb.dword = utf32_value;
    
    byte1 = wb.bytes.b1;
    Note... this will expose you to Endian issues, so the order of bytes in the example may not be correct for all cases.
    Last edited by CommonTater; 01-15-2012 at 09:57 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Casting from struct to char array and vice versa
    By Edelweiss in forum C Programming
    Replies: 6
    Last Post: 08-08-2011, 10:35 PM
  2. casting struct to struct
    By klmdb in forum C Programming
    Replies: 6
    Last Post: 08-14-2010, 02:29 PM
  3. struct holding data inside a linked list struct
    By icestorm in forum C Programming
    Replies: 2
    Last Post: 10-06-2009, 12:49 PM
  4. Advantages of c++ type casting over c type casting
    By kaibalya2008 in forum C++ Programming
    Replies: 10
    Last Post: 05-05-2009, 11:09 AM
  5. Casting a struct for sending to socket
    By chrisjmoss in forum Networking/Device Communication
    Replies: 6
    Last Post: 04-08-2008, 09:11 AM