Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

A byte reversal cheatsheet.

Posted by peeterjoot on July 29, 2010


#include <stdio.h>
#include "osstype.h"

int main()
{
   union {
      Uint64 u64 ;
      Uint32 u32[sizeof(Uint64)/sizeof(Uint32)] ;
      Uint16 u16[sizeof(Uint64)/sizeof(Uint16)] ;
      Uint8 u8[sizeof(Uint64)/sizeof(Uint8)] ;
   } u ;

   u.u64 = U64(0x0123456789abcdef) ;

   printf( "Uint64: 0x%016llX\n", u.u64 ) ;

   printf( "Uint32: " ) ;
   for ( int i = 0 ; i < sizeof(Uint64)/sizeof(Uint32) ; i++ )
   {
      printf( "0x%08X ", (unsigned)u.u32[i] & 0xFFFFFFFF ) ;
   }
   printf( "\n" ) ;

   printf( "Uint16: " ) ;
   for ( int i = 0 ; i < sizeof(Uint64)/sizeof(Uint16) ; i++ )
   {
      printf( "0x%04X ", (unsigned)u.u16[i] & 0xFFFF ) ;
   }
   printf( "\n" ) ;

   printf( "Uint8: " ) ;
   for ( int i = 0 ; i < sizeof(Uint64)/sizeof(Uint8) ; i++ )
   {
      printf( "0x%02X ", (unsigned)u.u8[i] & 0xFF ) ;
   }
   printf( "\n" ) ;

   return 0 ;
}

output when run on a little endian platform:

Uint64: 0x0123456789ABCDEF
Uint32: 0x89ABCDEF 0x01234567
Uint16: 0xCDEF 0x89AB 0x4567 0x0123
Uint8: 0xEF 0xCD 0xAB 0x89 0x67 0x45 0x23 0x01
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: