Path: utzoo!news-server.csri.toronto.edu!rutgers!dimacs.rutgers.edu!mips!sdd.hp.com!wuarchive!ukma!aunro!ersys!markt From: ersys!markt@nro.cs.athabascau.ca (Mark Tarrabain) Newsgroups: comp.lang.c Subject: Re: Portability vs. Endianness Message-ID: Date: 14 Mar 91 07:44:22 GMT References: <1991Mar12.105451.19488@dit.upm.es> Organization: Edmonton Remote Systems, Edmonton, AB, Canada Lines: 55 esink@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