Skip to content

Instantly share code, notes, and snippets.

@timofurrer
Created June 4, 2012 12:29
Show Gist options
  • Save timofurrer/2868069 to your computer and use it in GitHub Desktop.
Save timofurrer/2868069 to your computer and use it in GitHub Desktop.
make use of anonym union in struct in c
gcc -Wall -o union union.c
#include <stdio.h> // printf
#include <inttypes.h> // uint8_t, uint16_t, uint64_t
#include <string.h> // memset
struct mac_t
{
union
{
uint64_t mac;
struct
{
uint8_t byte6;
uint8_t byte5;
uint8_t byte4;
uint8_t byte3;
uint8_t byte2;
uint8_t byte1;
uint16_t dummy;
} __attribute__((__packed__));
};
} __attribute__((__packed__));
int main( void )
{
// 78:ac:c0:a5:e3:5e
struct mac_t m;
memset( &m, 0, sizeof( m ));
m.mac = 0x78acc0a5e35ell;
printf( "My mac is: %llx\n", m.mac );
printf( "My mac byte1: %x\n", m.byte1 );
printf( "My mac byte2: %x\n", m.byte2 );
printf( "My mac byte3: %x\n", m.byte3 );
printf( "My mac byte4: %x\n", m.byte4 );
printf( "My mac byte5: %x\n", m.byte5 );
printf( "My mac byte6: %x\n", m.byte6 );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment