Path: utzoo!news-server.csri.toronto.edu!rutgers!apple!usc!elroy.jpl.nasa.gov!swrinde!zaphod.mps.ohio-state.edu!rpi!uupsi!sunic!fuug!news.funet.fi!hydra!cc.helsinki.fi!wirzenius From: wirzenius@cc.helsinki.fi (Lars Wirzenius) Newsgroups: comp.lang.c Subject: Re: Portability vs. Endianness Message-ID: <1991Mar13.173420.5527@cc.helsinki.fi> Date: 13 Mar 91 17:34:20 GMT References: <1991Mar12.105451.19488@dit.upm.es> Organization: University of Helsinki Lines: 49 In article <1991Mar12.105451.19488@dit.upm.es>, esink@turia.dit.upm.es writes: >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 think you're going to have difficulties on machines with non-32-bit longs and non-8-bit chars. longs bigger than 32 bits won't fit into a 68000 longword (32 bits) without losing information. On machines with 32-bit longs and 8-bit bytes, you could try the following: #include #define BITS_PER_CHAR 8 int main() { unsigned long var; char Bytes[sizeof var]; unsigned long mask; int i; var = 0x12345678; printf("var = %lx\n", var); mask = ~(~0 & (~0 << BITS_PER_CHAR)); /* this creates a mask with only the lower * BITS_PER_CHAR bits turned on */ for (i = 0; i < sizeof var; ++i) { Bytes[ (sizeof var) - i - 1] = (var & mask); var >>= BITS_PER_CHAR; } for (i = 0; i < sizeof var; ++i) printf("Byte %d: %02x\n", i, Bytes[i]); exit(0); } This has been tested on a VAX (real good example, I know, but I can't try it on anything else right now). -- Lars Wirzenius wirzenius@cc.helsinki.fi