Endian problem on STM32

Embedded systems will always have the big-endian/little-endian issue. My personal approach has been to always encode internal memory with the native endianiness and make any swaps right when data enters or leaves.

I load the data using spi reads into analogin0.spibytes[0]-[2], with [0] as the MSB

By loading [0] as the MSB, you're encoding the value as big-endian.

analogin0.spibytes[0]=0xFF and and analogin0.spibytes[1]=0xB5, analogin0.halfwords[0] was equal to 0xB5FF

This indicates that the processor is little-endian.

If instead, you load the first value into [2] and work back to [0], then you've encoded the incoming number as little-endian, essentially making the swap as the number enters. Once you're working with the native representation, you can return to your original approach of using arithmetic operations. Just make sure to flip it back to big-endian when you transmit the value.


Regarding bounty "Really want to know about srm32f4 big endian mode", there is no big endian mode on this chip. STM32F4 does all memory access in little endian.

The user manual http://www.st.com/web/en/resource/technical/document/programming_manual/DM00046982.pdf mentions this on page 25. But there is more. On page 93 you can see there are endian swapping instructions. REV and REVB for reverse and reverse bit. REV will change endianess for 32 bits and REV16 will do it for 16 bit data.


Here is a code snippet for a cortex M4, compiled with gcc

/*
 * asmLib.s
 *
 *  Created on: 13 mai 2016
 */
    .syntax unified
    .cpu cortex-m4
    .thumb
    .align
    .global big2little32
    .global big2little16
    .thumb
    .thumb_func
 big2little32:
    rev r0, r0
    bx  lr
 big2little16:
    rev16   r0, r0
    bx  lr

From C, the call can be:

 extern uint32_t big2little32(uint32_t x);
 extern uint16_t big2little16(uint16_t x);

 myVar32bit = big2little32( myVar32bit );
 myVar16bit = big2little16( myVar16bit );

Don't know how to do faster than this :-)