Skip to content

Instantly share code, notes, and snippets.

@alexpirine
Created June 15, 2012 15:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save alexpirine/2936916 to your computer and use it in GitHub Desktop.
Save alexpirine/2936916 to your computer and use it in GitHub Desktop.
Endianness conversions with positive integers
// converts 32-bits positive integer to 4-bytes little endian
void to4li(unsigned long int const value, char * const buffer)
{
buffer[0] = value >> 8 * 0;
buffer[1] = value >> 8 * 1;
buffer[2] = value >> 8 * 2;
buffer[3] = value >> 8 * 3;
}
// converts 16-bits positive integer to 2-bytes little endian
void to2li(unsigned short const value, char * const buffer)
{
buffer[0] = value >> 8 * 0;
buffer[1] = value >> 8 * 1;
}
// converts 32-bits positive integer to 4-bytes big endian
void to4bi(unsigned long int const value, char * const buffer)
{
buffer[0] = value >> 8 * 3;
buffer[1] = value >> 8 * 2;
buffer[2] = value >> 8 * 1;
buffer[3] = value >> 8 * 0;
}
// converts 16-bits positive integer to 2-bytes big endian
void to2bi(unsigned short const value, char * const buffer)
{
buffer[0] = value >> 8 * 1;
buffer[1] = value >> 8 * 0;
}
// converts 4-bytes little endian to 32-bits positive integer
unsigned long int from4li(char const * const buffer)
{
unsigned long int value = 0;
value += (unsigned char) buffer[0] << 8 * 0;
value += (unsigned char) buffer[1] << 8 * 1;
value += (unsigned char) buffer[2] << 8 * 2;
value += (unsigned char) buffer[3] << 8 * 3;
return value;
}
// converts 2-bytes little endian to 16-bits positive integer
unsigned short int from2li(char const * const buffer)
{
unsigned short int value = 0;
value += (unsigned char) buffer[0] << 8 * 0;
value += (unsigned char) buffer[1] << 8 * 1;
return value;
}
// converts 4-bytes big endian to 32-bits positive integer
unsigned long int from4bi(char const * const buffer)
{
unsigned long int value = 0;
value += (unsigned char) buffer[0] << 8 * 3;
value += (unsigned char) buffer[1] << 8 * 2;
value += (unsigned char) buffer[2] << 8 * 1;
value += (unsigned char) buffer[3] << 8 * 0;
return value;
}
// converts 2-bytes big endian to 16-bits positive integer
unsigned short int from2bi(char const * const buffer)
{
unsigned short int value = 0;
value += (unsigned char) buffer[0] << 8 * 1;
value += (unsigned char) buffer[1] << 8 * 0;
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment