Make the frequent cases fast and the rare case correct

Program to find if a machine is big endian or little endian

I have a Intel processor laptop running a Linux OS. so the result of the program was a little endian. However to verify if the program is correct a bash script is run to check if it is correct .

For little endian lower-order byte of the number is stored in memory at the lowest address and for big endian higher-order byte is stored at lowest address.

#include "stdio.h"
#define BIG_ENDIAN 0
int main()
	int value;
	value = endian();
	if (value == 1)
	printf("Machine is little endian\n",value);
	printf("Machine is Big Endian\n",value);
int endian() {
short int word = 0x0001;
char *byte = (char *) &word;
return (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);

laptop:~/code$ ./a.out
Machine is little endian

laptop:~/code$ echo -n I | od -to2 | head -n1 | cut -f2 -d” ” | cut -c6

1 indicated its little endian.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: