EmbeddedRelated.com

Little Endian Converter Functions

Dr Cagri Tanriover February 18, 20131 comment Coded in C

Following are two functions that convert 16 bit and 32 bit unsigned numbers to their little endian versions. I have developed these in one of my embedded projects (on Atmega2560) and use them all the time. Despite their simplicity, I find them to be really useful and efficient. Since these functions are not platform specific, you can use them with no problem. I hope these will find use in your applications also.

unsigned short u16ToLittleEndian( unsigned short u16input )
{/* Use this function to convert a 16-bit number into little endian. */

  return( (u16input >> 8) ^ (u16input << 8) );

}// end u16ToLittleEndian()

unsigned long u32ToLittleEndian( unsigned long u32input )
{/* Use this function to convert a 32-bit number into little endian. */

  return( (u32input >> 24)
           ^ ( (u32input >> 8) & 0x000FF00 )
           ^ ( (u32input << 8) & 0x00FF0000 )
           ^ ( (u32input << 24) & 0xFF000000 )
         );

}// end u32ToLittleEndian()