Endian

Some code to test if your artchitecture is little or big endian

See https://en.wikipedia.org/wiki/Endianness

Code inspired by this page

In the figures below the 32 bit int is 0x0A0B0C0D So lsb byte is 0D

Little endian is where lsb byte is stored at lowest adress in memory (“a”)

Big endian is where msb byte is stored at lowest adress in memory (“a”)

 

Little endian

 

Big endian

Arduino

// inspireret af https://helloacm.com/how-to-find-out-whether-a-machine-is-big-endian-or-little-endian-in-cc/

#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1

int testByteOrder()
{
  int v = 0x01;
  char *b = (char *) &v;

  if (*b == 0x01)
    return LITTLE_ENDIAN;
  else
    return BIG_ENDIAN;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Endian test");

  if (testByteOrder() == BIG_ENDIAN)
    Serial.println("BIG ENDIAN arch");
  else
    Serial.println("LITTLE ENDIAN arch");

  Serial.print("size of int ");
  Serial.println(sizeof(int));
}

void loop() { }

C version on a std OS

#include <stdio.h>

#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1

int testByteOrder()
{
  int v = 0x01;
  char *b = (char *) &v;

  if (*b == 0x01)
    return LITTLE_ENDIAN;
  else
    return BIG_ENDIAN;
}

void main () {

  printf("\nEndian test\n");

  if (testByteOrder() == BIG_ENDIAN)
    printf("BIG ENDIAN arch\n");
  else
    printf("LITTLE ENDIAN arch\n");

  printf("size of int: %li\n",sizeof(int));
}

The hackers version (from wikipedia)

https://en.wikipedia.org/wiki/Endianness

...
#include <stdio.h>
#include <stdint.h>

union {
    uint8_t u8; uint16_t u16; uint32_t u32; uint64_t u64;
} u = { .u64 = 0x4A };

void main()
{
  puts("endian test\n");
  puts(u.u8 == u.u16 && u.u8 == u.u32 && u.u8 == u.u64 ? "true" : "false");
}