Mail Archives: djgpp/2001/06/15/09:12:42
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
- Raw text -