Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!bcm!shell!shell!rjohnson From: rjohnson@shell.com (Roy Johnson) Newsgroups: comp.lang.c Subject: Re: Portability vs. Endianness Message-ID: Date: 15 Mar 91 16:02:22 GMT References: <1991Mar12.105451.19488@dit.upm.es> Sender: usenet@shell.shell.com (USENET News System) Organization: Shell Development Company, Bellaire Research Center, Houston, TX Lines: 39 In-Reply-To: ersys!markt@nro.cs.athabascau.ca's message of 14 Mar 91 07:44:22 GMT 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. I posted yesterday in response to this, but managed to cover my face with egg. The real question I had should have gone something like this: Would tempstr, after sprintf(tempstr, "%08x", var); be independent of: 1) the endianness of the datatype var 2) the internal representation ? If so, then you could check strlen(tempstr) to make sure it's not too long, and convert the two-byte substrings of tempstr to the bytes they represent, e.g. #define mask(ch) (char)(((ch >= 'a') && (ch <= 'f')) ? ch-'a'+0xa : ch-'0') for (i=0; i<4; ++i) Bytes[i] = (mask(tempstr[2*i]) << 4) | mask(tempstr[2*i + 1]) -- ======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson ======= Feel free to correct me, but don't preface your correction with "BZZT!" Roy Johnson, Shell Development Company