some algorithmic puzzles, tutorials, interview questions... and stuff...

Sunday, September 06, 2009

How to convert a number from little endian to big endian

Converting from little endian to big endian means actually reversing the bits in a number, like in a mirror. This can be done iteratively, by removing one bit at a time and building another number with the bits reversed. I don't know any other version, but I don't think there's a better solution.

   1:      //little endian to big endian
   2:      unsigned char littleEndianN = 5;
   3:      cout << (unsigned int)littleEndianN << "(size=" << sizeof(littleEndianN) * 8 << ") little endian is ";
   4:      unsigned char bigEndianN = 0;
   5:      for (int i = 0; i < sizeof(littleEndianN) * 8; i++) {
   6:          cout << (littleEndianN & 1);
   7:          bigEndianN |= (littleEndianN & 1);
   8:          littleEndianN >>= 1;
   9:          if (i < (sizeof(littleEndianN) * 8 - 1))
  10:              bigEndianN <<= 1;
  11:      }
  12:      cout << " meaning " << (unsigned int)bigEndianN << " in big endian" << endl;

Here's what this prints:
   1:  5(size=8) little endian is 10100000 meaning 160 in big endian

What happens if the number is negative? Well, if we change all the unsigned char's to char's, the program prints this:
   1:  -5(size=8) little endian is 11011111 meaning -33 in big endian

Do you know why?
Also since we're on the subject, how do you tell if the computer representation is little endian or big endian? Spoiler below :)
   1:  bool isLittleEndian = ((1 << 1) == 2);


  1. It's possible to do it faster if you know the bitlength of the data type. Basically, you linearize that loop.

  2. converting the little endian to big endian is moving the lower Byte from the lower address to the high address. In the example above; the bits in the byte are moved from the lower to highest.

    Converting the little endian to big endian requires the knowledge whether the stream of byte coming is an integer(4 bytes long) or is a character(1 byte long) or is a double(8 byte long) or ... . Converting all these data types from little to big require the identification of the data type in the stream of byte

  3. sizeof(littleEndianN) does not work for that ?