Endianness

A brief Review of Endianness

A Method to Reverse Array

  • For example, if we want to reverse an array {1,2,3,4}, then we could follow these steps.
  1. Reverse adjacent 2 elements, and thus get {2,1,4,3}
  2. Divide array into blocks with size 2, i.e. { (2,1) , (4,3) }
  3. Repeat Step.1, then we get the answer { (4,3) (2,1) }
  • We can reverse any structure that can be abstracted into an array in the same way.
C++
/*Reverse Bits (Example)
  0x55555555; // 01010101010101010101010101010101
  0x33333333; // 00110011001100110011001100110011
  0x0f0f0f0f; // 00001111000011110000111100001111
  0x00ff00ff; // 00000000111111110000000011111111
*/

 uint32_t ReverseBits(uint32_t num)
 {
   num = num >> 1 & 0x55555555 | (num & 0x55555555) << 1;
   num = num >> 2 & 0x33333333 | (num & 0x33333333) << 2;
   num = num >> 4 & 0x0f0f0f0f | (num & 0x0f0f0f0f) << 4;
   num = num >> 8 & 0x00ff00ff | (num & 0x00ff00ff) << 8;
   return num >> 16 | num << 16;
 }
 
uint32_t ReverseEndianness(uint32_t num)
{
  num = num >> 8 & 0x00ff00ff | (num & 0x00ff00ff) << 8;
  return num >> 16 | num << 16;
}

Leave a Reply

Your email address will not be published. Required fields are marked *