[comp.lang.c] determining endian ?

dan@rna.UUCP (Dan Ts'o) (11/28/89)

	I'm sure this is old hat, but I recently needed to figure out if a
particular host machine was big-endian or little endian. Comments, please,
on this little snippet of code.
	Please email responses.
				Cheers,
				Dan Ts'o		212-570-7671
				Dept. Neurobiology	dan@rna.rockefeller.edu
				Rockefeller Univ.	...cmcl2!rna!dan
				1230 York Ave.		rna!dan@nyu.edu
				NY, NY 10021		tso@rockefeller.arpa
							tso@rockvax.bitnet

	integer i, j;
	char *s, *t;
	long lb;

	s = (char *)&lb;
	t = "0123456789";
	for (i = 0; i < sizeof (long); i++)	/* Probably not necessary */
		*s++ = t[i];			/* to fill everybody out */
	j = (lb&0377) - '0';
	if (j == 0)
		s = ENDIANLIL;
	else if (j == (sizeof (long) - 1))
		s = ENDIANBIG;
	else
		s = ENDIANUNKNOWN;	/* PDP-11 ??? */


	BTW, won't this fail for a PDP-11 (aren't PDP-11 longs backwards ?)

	I suppose, now that I look at it, this would be shorter...

	s = (char *)&lb;
	lb = -1L;
	s[0] = 0;
	i = sizeof (long) - 1;
	s[i] = i;
	j = (lb&0377) - '0';
	if (j == 0)
		s = ENDIANLIL;
	else if (j == i)
		s = ENDIANBIG;
	else
		s = ENDIANUNKNOWN;	/* PDP-11 ??? */

	How many machines are neither big nor little endian ? If none, then,

	s = (char *)&lb;
	lb = 1;
	if (*s)
		s = ENDIANLIL;
	else
		s = ENDIANBIG;

merlyn@iwarp.intel.com (Randal Schwartz) (11/30/89)

In article <858@rna.UUCP>, dan@rna (Dan Ts'o) writes:
| 	I'm sure this is old hat, but I recently needed to figure out if a
| particular host machine was big-endian or little endian. Comments, please,
| on this little snippet of code.
[code deleted]

Well, Larry Wall uses the following piece of code in his marvelous
Configure script (created with metaConfigure, of course).  The output
of the script gives the byte order as an integer, little-endian ending
up as 1234, big endian as 4321, and so on.

-------------------------------------------------- cut here
#include <stdio.h>
main()
{
    int i;
    union {
	unsigned long l;
	char c[sizeof(long)];
    } u;

    if (sizeof(long) > 4)
	u.l = 0x0807060504030201;
    else
	u.l = 0x04030201;
    for (i=0; i < sizeof(long); i++)
	printf("%c",u.c[i]+'0');
    printf("\n");
}
-------------------------------------------------- cut here

You could probably build your thing on top of this.

Just another C hacker,
-- 
/== Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ====\
| on contract to Intel's iWarp project, Hillsboro, Oregon, USA, Sol III  |
| merlyn@iwarp.intel.com ...!uunet!iwarp.intel.com!merlyn	         |
\== Cute Quote: "Welcome to Oregon... Home of the California Raisins!" ==/