Wednesday, January 25, 2012

Endianness: Different Processors

Endianness refers to the way data is represented in memory by different processors. For details about endianness you can refer

We will run below code on two different CPU architectures, Intel and MIPS
*******Start of Code endi.c ********

int main()
        int magiclhtona, magiclntoha, magiclhton1, magiclntoh1, htonli2, htonsi2, ntohli2, ntohsi2, htonli6, htonsi6, ntohli6, ntohsi6;
        magiclhtona = htonl(0xa1b2c3d4);
        magiclntoha = ntohl(0xa1b2c3d4);

        magiclhton1 = htonl(0x1f8b0800);
        magiclntoh1 = ntohl(0x1f8b0800);

        htonli2 = htonl(25);
        htonsi2 = htons(25);
        ntohli2 = ntohl(25);
        ntohsi2 = ntohs(25);

        htonli6 = htonl(65535);
        htonsi6 = htons(65535);
        ntohli6 = ntohl(65535);
        ntohsi6 = ntohs(65535);

        printf("magiclhtona=%p magiclntoha=%p,magiclhton1=%p, magiclntoh1=%p, htonli2=%d htonsi2=%d ntohli2=%d ntohsi2=%d, htonli6=%d, htonsi6=%d, ntohli6=%d, ntohsi6=%d\n", magiclhtona, magiclntoha, magiclhton1, magiclntoh1,htonli2, htonsi2, ntohli2, ntohsi2, htonli6, htonsi6, ntohli6, ntohsi6);
    return 0;

*******Endof Code endi.c ********
To understand the output we should know what is he endianness of the Processors we are using
Intel        Little Endian
MIPS     Big Endian

Output on Intel processor
[praveen]# ./endi
magiclhtona=0xd4c3b2a1 magiclntoha=0xd4c3b2a1,magiclhton1=0x88b1f, magiclntoh1=0x88b1f, htonli2=419430400 htonsi2=6400 ntohli2=419430400 ntohsi2=6400, htonli6=-65536, htonsi6=65535, ntohli6=-65536, ntohsi6=65535

Output on MIPS processor
praveen# ./endi
magiclhtona=0xa1b2c3d4 magiclntoha=0xa1b2c3d4,magiclhton1=0x1f8b0800, magiclntoh1=0x1f8b0800, htonli2=25 htonsi2=25 ntohli2=25 ntohsi2=25, htonli6=65535, htonsi6=65535, ntohli6=65535, ntohsi6=65535

Modify endi.c source file by adding below code
        int htonli8 = htonl(65538);
        int htonsi8 = htons(65538);
        int ntohli8 = ntohl(65538);
        int ntohsi8 = ntohs(65538);
       printf("htonli8=%d, htonsi8=%d, ntohli8=%d, ntohsi8=%d\n", htonli8, htonsi8, ntohli8, ntohsi8);

Output on Intel Processor
htonli8=33554688, htonsi8=512, ntohli8=33554688, ntohsi8=512

Output on MIPS Processor
htonli8=65538, htonsi8=2, ntohli8=65538, ntohsi8=2

Hope this will help someone somewhere to understand endianness on different Processors.

Other articles on C language

No comments:

Post a Comment