Message-ID: <3B29C402.C8C7097@acm.org> Date: Fri, 15 Jun 2001 14:14:59 +0100 From: Eric Sosman X-Mailer: Mozilla 4.72 [en] (Win95; U) X-Accept-Language: en MIME-Version: 1.0 Newsgroups: comp.os.msdos.djgpp To: djgpp AT delorie DOT com Subject: Re: big endian little endian, integer and unsigned short References: <5 DOT 0 DOT 2 DOT 1 DOT 1 DOT 20010615210251 DOT 00a99470 AT rsbsgpo DOT anu DOT edu DOT au> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Reply-To: djgpp AT delorie DOT com Katharina Siebke wrote: > > here is the problem in a different form: > > somebody did this code to me: > > int varint; > unsigned short varshort; > > varint = varshort <<16 > > how is the order of my bytes in an intel PC memory after this? Stop right there; you're asking the second question first. The first question you should ask is "What is the *value* of varshort?" because the effect of the << operator (indeed, of every C operator) is defined in terms of the value(s) of its operands, not their representation(s). With that in mind ... > varint was undefined > varshort was for example: 56 7F, then 7F is MSB and 56 is LSB (right?). On a Little-Endian machine like the PC, the two hexadecimal bytes 56 7F represent the *value* 0x7F56, or 32598. Applying <<16 gives the *value* 0x7F560000, or 2136342528. This value has the four-byte Little-Endian representation 00 00 56 7F. > is varint now : > > | starting address > v > 56 7F 00 00 (solution A) or > 00 00 56 7F (solution B) or > 7F 56 00 00 (solution C) or > 00 00 7F 56 (solution D) ???????? ... which you've labeled "solution B." > I need to know, but everything is turning in my haed. Try to think in terms of values, not representations, whenever possible -- and in most circumstances (more than many programmers realize at first), values *are* the appropriate conceptual framework and representations should be ignored or even abhorred. In the very few cases where representations are important (e.g., when you're indulging in the dubious practice of type-punning), it's still helpful to "convert" the input representations to values, consider the effects of the calculation on those values, and then convert the result value to its representation again. Purely representational shortcuts are fraught with opportunities for error. -- Eric Sosman esosman AT acm DOT org