Endianness

28 May 2018

keep getting mixed up on endianness - so here is a small test to show this stuff (to remind me not to check it again…)

  

	HOST BYTE ORDER - LITTLE ENDIAN
			Number: 0x1020304

	In memory:

	00000000  04 03 02 01                                       |....|
	00000004

	NETWORK BYTE ORDER - BIG ENDIAN
			Number: 0x1020304

	In memory:

	00000000  01 02 03 04                                       |....|
	00000004

   

Now host byte order (little endian) has the advantage that a uint16_t can be cast to uint32_t without changes;

Network byte order (big endian) is represented the same order as it is written (but the cast gets you the upper two bytes). However with network byte order your specifications map directly to how it is represented (that’s why it’s called network byte order).

This endian naming thing just confuses the customer - host/network byte order is a natural description of what is going on.

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>

main()
{
   uint32_t x;
   FILE *fp;

   x = 0x01020304;

   fprintf(stderr,"HOST BYTE ORDER - LITTLE ENDIAN\n\tNumber: 0x%x\n", x);
   fp = fopen("tr","w+");
   if (fp != NULL)
   {
        fwrite(&x,sizeof(x),1,fp);
        fclose(fp);
        fprintf(stderr,"\nIn memory:\n\n");
        system("hexdump -C tr");
   }

   fprintf(stderr,"\nNETWORK BYTE ORDER - BIG ENDIAN\n\tNumber: 0x%x\n", x);

   x= htonl(x);

   fp = fopen("tr" ,"w+");
   if (fp != NULL)
   {
        fwrite(&x,sizeof(x),1,fp);
        fclose(fp);
        fprintf(stderr,"\nIn memory:\n\n");
        system("hexdump -C tr");
   }
   return 0;
}