Technical Support

C51: CONVERTING BIG ENDIAN TO LITTLE ENDIAN


Information in this article applies to:

  • C51 Version 5.50
  • C51 Version 6.00

QUESTION

I have a memory mapped 16 bit peripheral that is Little Endian in format. How do I swap the order of the bytes in the word that I write out to the peripheral?

ANSWER

There are numerous ways to swap bytes in a 16-bit value. The following example uses the Mem_Swap function to swap the order of the bytes in the word argument that is passed. The new value for the word is returned.

// Memory Mapped I/O Device
xdata unsigned int io_dev _at_ 0x8000;

// Byte-swapping Function
unsigned int Mem_Swap (unsigned int value)
  {
  unsigned int rval;

  ((unsigned char *) &rval) [0] = ((unsigned char *) &value) [1];
  ((unsigned char *) &rval) [1] = ((unsigned char *) &value) [0];

  return (rval);
  }

void main (void)
  {
  io_dev = Mem_Swap (0xaa55);
  while (1){};
  }

Last Reviewed: Tuesday, January 18, 2000


Did this article provide the answer you needed?
 
Yes
No
Not Sure