Struct alignement/endianess check

Asked by At

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?

2 Answers

3
nos On Best Solutions

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]);
}
0
James Kanze On

I've got a template class that I usually use for this sort of thing:

template<typename T>
class Dump
{
    unsigned char const*myObj;
public:
    explicit            Dump( T const& obj )
    :   myObj( reinterpret_cast<unsigned char const*>( &obj ) )
    {
    }
    friend std::ostream& operator<<( std::ostream& dest, Dump const& obj )
    {
        IOSave              saver( dest ) ;
        dest.fill( '0' ) ;
        dest.setf( std::ios::hex, std::ios::basefield ) ;
        char const*         baseStr = "" ;
        if ( (dest.flags() & std::ios::showbase) != 0 ) {
            baseStr = "0x" ;
        }
        unsigned char const* const
                            end = obj.myObj + sizeof( T ) ;
        for ( unsigned char const* p = myObj ; p != end ; ++ p ) {
            if ( p != myObj ) {
                dest << ' ' ;
            }
            dest << baseStr << std::setw( 2 ) << (unsigned int)( *p ) ;
        }
    }
} ;

template< typename T >
inline Dump< T >
dump(
    T const&            obj )
{
    return Dump< T >( obj ) ;
}

(IOSave is just the usual class to save and restore the formatting parameters when they're going to be modified.)

This allows dumping a hex image of pretty much anything, just by writing:

std::cout << dump( myObj ) << std::endl;