Portability vs. Endianness
Lars Wirzenius
wirzenius at cc.helsinki.fi
Thu Mar 14 03:34:20 AEST 1991
In article <1991Mar12.105451.19488 at dit.upm.es>, esink at 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 <stdio.h>
#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 at cc.helsinki.fi
More information about the Comp.lang.c
mailing list