Search code examples
c++structure

Struct alignment/endianess check


I have this kind of C structure.

struct uart_buff
{
    uart_buff(uint32_t reg_Addr, uint32_t uValue)
    {
        addr=reg_Addr;
        data=uValue;
        terminator=0xFF;
    }
    uint32_t addr;
    uint32_t data;
    uint8_t terminator;
};

I would to print each byte (9 if I'm right) of this struct (as an Hexadecimal value) in order to check if the syntax is correct. Is there a simple way to do such a thing?


Solution

  • Yes, you can access the struct through an unsigned char pointer,

    struct uart_buff buf = ...;
    unsigned char *p = (unsigned char *)&buf;
    size_t i;
    
    for(i = 0; i < sizeof buf; i++) {
     printf("%02X ", p[i]);
    }