Skip to content

Instantly share code, notes, and snippets.

@manvscode
Created April 26, 2013 19:58
Show Gist options
  • Save manvscode/5470046 to your computer and use it in GitHub Desktop.
Save manvscode/5470046 to your computer and use it in GitHub Desktop.
Versatile functions for converting endianess.
typedef union two_bytes {
unsigned short s;
unsigned char bytes[ 2 ];
} two_bytes_t;
int is_big_endian( void )
{
two_bytes_t check;
check.s = 1;
if( check.bytes[ 0 ] == 1 )
{
return 0; /* little endian */
}
return 1;
}
void swap_every_two_bytes( void* mem, size_t size )
{
unsigned char* buffer = (unsigned char*) mem;
/* If we have an odd number of bytes, then
* we subtract 1 and swap up until that size.
*/
size -= (size % 2);
for( size_t i = 0; i < size - 1; i += 2 )
{
unsigned char tmp = buffer[ i ];
buffer[ i ] = buffer[ i + 1];
buffer[ i + 1 ] = tmp;
}
}
void hton( void *mem, size_t size )
{
if( !is_big_endian( ) )
{
swap_every_two_bytes( mem, size );
}
}
void ntoh( void *mem, size_t size )
{
if( !is_big_endian( ) )
{
swap_every_two_bytes( mem, size );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment