English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How to write a C program that will print 1 when compiled and run on a little-endian machine and will print 0 when complied and run on a big-endian machine. The program should run on any machine regardless of its word size. (You can assume that a variable declared as unsigned char occupies one byte.)

2007-02-01 10:35:07 · 3 answers · asked by highsharp06 1 in Computers & Internet Programming & Design

3 answers

check out http://www.pscode.com for great sample codes.

2007-02-01 14:05:04 · answer #1 · answered by Richard H 7 · 0 0

#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1

int TestByteOrder()
{
short int word = 0x0001;
char *byte = (char *) &word;
return(byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}
This code assigns the value 0001h to a 16-bit integer. A char pointer is then assigned to point at the first (least-significant) byte of the integer value. If the first byte of the integer is 0x01h, then the system is Little-Endian (the 0x01h is in the lowest, or least-significant, address). If it is 0x00h then the system is Big-Endian.

Similarly,

bool IsBigEndian()
{
short word = 0x4321;
if((*(char *)& word) != 0x21 )
return true;
else
return false;
}

2007-02-01 20:46:08 · answer #2 · answered by Anonymous · 0 0

You need to detect that programatically.

If you pack an integer byte by byte, then when you resolve that integer, you can determine the endianness of a pc by checking two-byte versions of that number (shorts).

Try playing with that in a program and see where it takes you.

Good luck!

2007-02-01 20:19:12 · answer #3 · answered by Anonymous · 0 0

fedest.com, questions and answers