determining endian ?

Dan Ts'o dan at rna.UUCP
Tue Nov 28 09:48:41 AEST 1989


	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 at rna.rockefeller.edu
				Rockefeller Univ.	...cmcl2!rna!dan
				1230 York Ave.		rna!dan at nyu.edu
				NY, NY 10021		tso at rockefeller.arpa
							tso at 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;



More information about the Comp.lang.c mailing list