From 1397764407821505742
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,738ae3371beb3408
X-Google-Attributes: gidf78e5,public
From: Steve Clamage <stephen.clamage@sun.com>
Subject: Re: portable method of determining endianness byte order.
Date: 1999/12/01
Message-ID: <384588BB.E3DB6EC9@sun.com>#1/1
X-Deja-AN: 555483867
X-NNTP-Posting-Host: taumet.eng.sun.com
Content-Transfer-Encoding: 7bit
Approved: stephen.clamage@sun.com (comp.std.c++)
References: <38329967.470B6CED@hqs.mid.gmeds.com> <38359FF5.AB0B77E9@zetec.com> <t73dtnacpa.fsf@calumny.jyacc.com> <g1pNRNAk6GR4Ew21@robinton.demon.co.uk> <823p8g$6gj@library1.airnews.net>
X-Accept-Language: en
X-UID: 0000000001
X-Status: $$$T
Content-Type: text/plain; charset=us-ascii
Organization: Sun Microsystems
Mime-Version: 1.0
Newsgroups: comp.std.c++
Originator: clamage@taumet


Bill Wade wrote:
> 
> Francis Glassborow wrote in message ...
> > ... why do you assume that [integer endianess] is a
> >simple two way choice?
> 
> Maybe the original poster read read footnote 44 (associated with 3.9.1/7)
> which strongly implies that adjacent bits represent adjacent powers of two.
> It takes some imagination to suppose that two bits in separate bytes can be
> adjacent to each other, if their bytes aren't adjacent to each other.  It
> would seem that the least significant byte of an integer must be at one end,
> and the most significant at the other, with any intermediate bytes in a
> uniform order.  Thus a simple two way choice.

I don't think you can write a C++ program having defined behavior that
can tell what byte order is used in physical memory. That is, the
requirement on a "pure binary representation" affects the observable
behavior of operations like shifting and masking. For example, you are
guaranteed that for an int k, 0<=k<=(INT_MAX/2) implies (k*2)==(k<<1),
and that (0x12345678 & 0x0000FF00)==0x5600.

I don't think there are any guarantees in the standard about what
happens when you extract arbitrary bytes from an object in memory,
however. For example, if you write
	int k = 0x12345678; // 32-bit int, 8-bit bytes
	unsigned char* p = (unsigned char*)&k + 2;
	cout << hex << *p;
the operations are valid in the sense that no undefined behavior is
involved, but I don't think you can expect to see 34 (little-endian)
or 56 (big-endian) as the output.

-- 
Steve Clamage, stephen.clamage@sun.com


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]




