Portability vs Endianness
Donald McLachlan
don at dgbt.doc.ca
Sat Mar 16 00:55:26 AEST 1991
>Sender: @dit.upm.es
>
>
>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.
>
>Feel free to suggest your own declarations
>to replace or augment mine.
>
>Thanks in advance for the input,
>
>Eric
>
Eric:
I can't be completely sure (I've only checked it on 2 different architectures)
and done dry runs in my head for 2 others, but I think whis should work.
Please don't flame me for posting this guys, because since I don't know
if this will work I want some input.
Don.
_______________________ cut ________________________________________
static int init = 1;
static char to_motorola[sizeof(long)];
main()
{
extern long cvt_to_moto();
char format_string[32];
int i;
long number;
char *c = (char *)&number;
number = 0x574319;
sprintf(format_string, "number = 0x%%0%dlx\n", sizeof(number) * 2);
printf(format_string, (unsigned long)number);
printf("local order = ");
for(i = 0; i < sizeof(number); ++i)
printf("%02lx ", (unsigned long)c[i]);
puts("");
number = cvt_to_moto(number);
printf("moto order = ");
for(i = 0; i < sizeof(number); ++i)
printf("%02lx ", (unsigned long)c[i]);
puts("");
}
long cvt_to_moto(host_num)
long host_num;
{
char *native, *motorola;
int i;
long moto_num;
if(init == 1)
init_cvt_to_moto();
native = (char *)&host_num;
motorola = (char *)&moto_num;
for(i = 0; i < sizeof(moto_num); ++i)
motorola[i] = native[to_motorola[i]];
return(moto_num);
}
init_cvt_to_moto()
{
int i;
long num;
char *c = (char *)#
for(i = 0; i < sizeof(num); ++i) /* build moto-endian image */
c[i] = i; /* of 0x00010203... */
for(--i; i >= 0; --i) /* for each byte in num */
{ /* read LSB bytes from num */
to_motorola[i] = num & 0x00FFL; /* and put in to_moto[LSB] */
num >>=8; /* get next byte in num */
}
init = 0;
}
_______________________ cut ________________________________________
here are the results from a Vax 750 running Ultrix
number = 0x00574319
local order = 19 43 57 00
moto order = 00 57 43 19
and from a sun sparcstation 330 running Sun0/S
number = 0x00574319
local order = 00 57 43 19
moto order = 00 57 43 19
More information about the Comp.lang.c
mailing list