Page 1 of 1

Endianness macros

Posted: Wed Jul 15, 2015 11:57 am
by TexZK
Hello Giovanni,
I am developing some register mapping for cross-platform code. You chose C99 as the standard in ChibiOS 3, and that's a wise choice IMHO. C99 provides the stdint.h header with portable integer types, but the standard still lacks any portable way to determine the architecture endianness at compile time. There are some nice tricks, but they don't work in the preprocessor.

So, what I ask to you is: are you willing to put a preprocessor symbol to tell the endianness of the ported architecture? I think it will be a very useful addition to ChibiOS, because that way it is possible to generate register type mappings with portable unions, by declaring bit fields in both orders, and compiling only the target one.

For example, in ch.h (or elsewere):

Code: Select all

#define CH_ENDIANNESS_LITTLE 0x1234
#define CH_ENDIANNESS_BIG    0x4321

In the port header:

Code: Select all

#define CH_ENDIANNESS CH_ENDIANNESS_LITTLE

In user library code:

Code: Select all

union mybitfield {
#if CH_ENDIANNESS == CH_ENDIANNESS_LITTLE
  uint8_t lsb : 1;
  uint8_t msb : 1;
#elif CH_ENDIANNESS == CH_ENDIANNESS_BIG
  uint8_t msb : 1;
  uint8_t lsb : 1;
#else
#error "Unknown CH_ENDIANNESS value"
#endif
};


Do you think this will be useful? I would also write a library for endianness conversion into the community repository if needed (something like the htons() and related stuff).
Since protocols and low-level access to data structures is common in the embedded field, such features are very appreciated and easy to use.
If there is already a way to do that, my fault ;)

Re: Endianness macros

Posted: Wed Jul 15, 2015 12:22 pm
by Giovanni
Apparently GCC already defines endianness macros, see: http://stackoverflow.com/questions/1001 ... -c-program

I will look into adding it in chtypes.h in a compiler-independent way.

Giovanni

Re: Endianness macros

Posted: Wed Jul 15, 2015 12:25 pm
by Giovanni
This is also interesting: http://esr.ibiblio.org/?p=5095

Giovanni

Re: Endianness macros

Posted: Wed Jul 15, 2015 12:45 pm
by barthess
I am pretty sure that endiannes can not be detected at compile time.
Because compiler does not care about this. Moreover Cortex-M3 has ability
to switch endiannes at any time. So as a minimal evil I have defined
endiannes in separated header and check it at a top of main() function
using union trick.

Re: Endianness macros

Posted: Wed Jul 15, 2015 1:45 pm
by steved
The LWIP interface already has a symbol BYTE_ORDER (= BIG_ENDIAN or LITTLE_ENDIAN) (defined in various/lwip_bindings/cc.h

As one of the references said, you don't normally swap endianness in mid-execution - must say I can't quickly think of a use case ATM, and its a piece of complexity that Chibi could well do without supporting, IMHO. So a preprocessor symbol seems a good idea to me.