Portability vs. Endianness

Roy Johnson rjohnson at shell.com
Sat Mar 16 02:02:22 AEST 1991


esink at turia.dit.upm.es writes:

> Given the following :
> 
> long var;
> unsigned char Bytes[4];
> 
> 
> Is there a portable way to move the value held in var
> into the memory space pointed to by Bytes, with the restriction
> that the representation be in Most Significant Byte first
> format ?  I am well aware that sizeof(long) may not be 4.  I
> want the value contained in var converted to a 68000
> long word, and I want the code fragment to run on any
> machine.  The solution must be ANSI C.

I posted yesterday in response to this, but managed to cover my
face with egg.  The real question I had should have gone something
like this:

Would tempstr, after
 sprintf(tempstr, "%08x", var);
be independent of:
1) the endianness of the datatype var
2) the internal representation
?

If so, then you could check strlen(tempstr) to make sure it's not
too long, and convert the two-byte substrings of tempstr to
the bytes they represent, e.g.

#define mask(ch) (char)(((ch >= 'a') && (ch <= 'f')) ? ch-'a'+0xa : ch-'0')

for (i=0; i<4; ++i)
  Bytes[i] = (mask(tempstr[2*i]) << 4) | mask(tempstr[2*i + 1])
--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list