Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Swapping endianess

Help
A Hoyle
2008-12-11
2013-03-12
  • A Hoyle
    A Hoyle
    2008-12-11

    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.

    Thanks

    AHoyle

    SDCC 2.8.0 on SiLabs F330

     
    • Patryk
      Patryk
      2008-12-12

      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:
      #if COMPILER_IS_BIG_ENDIAN
      #define BE16(x) x
      #define LE16(x) ( ((x)<<8) | (((x)>>8) & 0xFF) )
      #else
      #define BE16(x) ( ((x)<<8) | (((x)>>8) & 0xFF) )
      #define LE16(x) x
      #endif

      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);
        (...)
        return;
      }

      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.