Portability vs. Endianness
Mark Tarrabain
ersys!markt at nro.cs.athabascau.ca
Thu Mar 14 17:44: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.
>
try the following code fragment: (no guarantees mind you, It's late at
night and I'm kinda wired on caffeine)
union swap_type
{
long lvalue;
char cvalue[4];
};
int hifirst()
{
union swap_type dummy;
dummy.lvalue = 1;
return dummy.cvalue[3];
}
void put_var_to_bytes(long var,char Bytes[4])
{
union swap_type dummy;
dummy.lvalue = var;
if (!hifirst())
{
char temp;
temp = dummy.cvalue[0];
dummy.cvalue[0] = dummy.cvalue[3];
dummy.cvalue[3] = temp;
temp = dummy.cvalue[1];
dummy.cvalue[1] = dummy.cvalue[2];
dummy.cvalue[2] = temp;
}
Bytes[0] = dummy.cvalue[0];
Bytes[1] = dummy.cvalue[1];
Bytes[2] = dummy.cvalue[2];
Bytes[3] = dummy.cvalue[3];
}
this is slightly machine dependant - it assumes that the size of a long
is the same as 4 characters. (which should be the case on a 68000
anyways)
>> Mark
More information about the Comp.lang.c
mailing list