Monday, May 24, 2010

How to I write a C program???

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.)

How to I write a C program???
check out http://www.pscode.com for great sample codes.
Reply:#define BIG_ENDIAN 0


#define LITTLE_ENDIAN 1





int TestByteOrder()


{


short int word = 0x0001;


char *byte = (char *) %26amp;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 *)%26amp; word) != 0x21 )


return true;


else


return false;


}
Reply: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!


No comments:

Post a Comment