Solve Puzzles Publish an Article

Connect to us Using



    Get Free Article Updates


Endianness and Byte-Order

+9 votes

Endian or endianness, refer to how bytes of a data word are ordered within memory.

Big-endian systems are systems in which the most significant byte of the word is stored in the smallest address given and the least significant byte is stored in the largest. (As shown in the following figure)
Big Endian

Little endian systems are those in which the least significant byte is stored in the smallest address and and the most significant byte is stored in the largest. (As shown in the following figure)
Little Endian

Byte-Order is a terms which is used as a proxy of the Endianness which means how bytes are ordered or transferred over wire. Byte-Order can be classified in the following ways

Host-Byte Order represents how the bytes/word is stored into the computer memory it can be little endian or big endian. Where as Network byte order represents how bytes are transferred over the wire which is always least significant byte and is same as big-endian.

Functions to convert Network-Byte order to Host-Byte or vice-versa
unsigned short htons(unsigned short hostshort): This function converts 16-bit (2-byte) quantities from host byte order to network byte order.

unsigned long htonl(unsigned long hostlong): This function converts 32-bit (4-byte) quantities from host byte order to network byte order.

unsigned short ntohs(unsigned short netshort): This function converts 16-bit (2-byte) quantities from network byte order to host byte order.

unsigned long ntohl(unsigned long netlong): This function converts 32-bit quantities from network byte order to host byte order.

Program to determine Endianness of the machine

#include <stdio.h>

int main(int argc, char **argv)
{
    union {
        short s;
        char c[sizeof(short)];
    }un;
    un.s = 0x0502;

    if (sizeof(short) == 2) {
        if (un.c[0] == 5 && un.c[1] == 2)
            printf("big-endian\n");
        else if (un.c[0] == 2 && un.c[1] == 5)
            printf("little-endian\n");
        else
            printf("unknown\n");
   } else{
        printf("sizeof(short) = %d\n", sizeof(short));
   }
   exit(0);
}
posted Jan 8 by Amit Mishra
  Promote This Article
    

HyperSmash
Blog Directory | Submit to Directories and Promote your Blogs
...