Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!uunet!yale!cmcl2!rna!dan From: dan@rna.UUCP (Dan Ts'o) Newsgroups: comp.lang.c Subject: determining endian ? Message-ID: <858@rna.UUCP> Date: 27 Nov 89 22:48:41 GMT Organization: Rockefeller University - Neurobiology Lines: 55 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;