Swapping endianess

A Hoyle
  • A Hoyle
    A Hoyle

    Hi All

    I am working on an application which requires me to send and read all my data in big endian format (MSB in lower byte address). I know SDCC uses little endian. Is there any easy / efficient way to tell the complier that some variables are stored in big endian, so must be swapped before using them. I have noticed that the compiler seem to copy value from the external memory into the register before doing any maths on them, so it could easily swap the byte as it copies them. Is this possible?

    If not I will have to hand code it in assembler, but doing it in C would be much nicer.



    SDCC 2.8.0 on SiLabs F330

    • Patryk

      Didn't heard of compiler able to switch endiannes. Some platforms (ARM7 for example) allows it. Usually you must swap bytes in buffer when received, process it in efficient way, and swap again on sending. If you can't do this (constants in ROM for example), you can use macros - there may be even portable:
      #define BE16(x) x
      #define LE16(x) ( ((x)<<8) | (((x)>>8) & 0xFF) )
      #define BE16(x) ( ((x)<<8) | (((x)>>8) & 0xFF) )
      #define LE16(x) x

      typedef struct
        unsigned char a;
        unsigned int b;
      } TStr_le;

      unsigned int Str_sum(const TStr_le * const str)
        return str->a + LE16(str->b);
      void f(TStr_le * const str)
        str->b = LE16(0x1234);

      But swapping bytes using macros (on every access) may be very inefficient - this is the case with SDCC when I checked it some time ago. But with proper optimization they can be very efficient on 8 bit platforms.