This blog is under construction

Saturday 13 July 2013

C program to check big indian or little indian

Write a C program to find endianness(Big Endian/Little Endian) of a macine.
Consider a four byte data 0x01020304(0x01, 0x02, 0x03, 0x04).  Let us see how the data would be stored in Big Endian and Little Endian machines.

Big Endian:  (Most Significant Byte to Least Significant Byte)
               +--------------------------------+
Data      : | 0x01 | 0x02 | 0x03 | 0x04 |
              +--------------------------------+
Memory:       a       a + 1   a + 2   a + 3

Little Endian: (LSB to MSB)
               +--------------------------------+
Data      : | 0x04 | 0x03 | 0x02 | 0x01 |
               +--------------------------------+
Memory :      a      a + 1   a + 2    a + 3

How to find Endianess of a machine?
Step 1: Get an integer from user(1 to 15).  The size of integer is 4 byte.
Step 2: Fetch the data in every byte of the given input(integer).
Step 3: If the first byte is zero, then the user's machine is Big endian.  Otherwise, little endian.

Example: 0x0f
Data in Big Endian Machine:
+----------------------------+
| 0x0 | 0x0 | 0x0 | 0x0f  | - first byte is zero.  So, user's machine is big endian.
+----------------------------+

Data in Little Endian Machine:
+--------------------------+
| 0xf | 0x0 | 0x0 | 0x0 | -  first byte is non-zero.  So, user's machine is little endian.
+--------------------------+



  #include <stdio.h>
  int main () {
        int num, i, val;
        char *ptr;

        /* get the integer input from user */
        printf("Enter your input(1 - 15):");
        scanf("%d", &num);

        if (num < 1 || num > 15) {
                printf("Thresh Level Exceeded!!\n");
                return 0;
        }

        ptr = (char *)(&num);

        printf("Hexadecimal value of %d is 0x%x\n", num, num);

        /* Scanning 4 byte data - byte by byte */
        printf("Data in memory: ");
        for (i = sizeof(int) - 1; i >= 0; i--) {
                val = *(ptr + i);
                printf("|0x%x", val);
        }
        printf("|\n");

        /* data in first byte */
        val = *ptr;

        /* print the result */
        if (!val) {
                printf("Your Machine is Little Indian!!\n");
        } else {
                printf("Your Machine is Big Indian!!\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input(1 - 15):15
  Hexadecimal value of 15 is 0xf
  Data in memory: |0x0|0x0|0x0|0xf|
  Your Machine is Big Indian!!


No comments:

Post a Comment