"Tim Astle" <[EMAIL PROTECTED]> wrote:

> Okay, I found a logic problem as well.  This is weird because I remember
> doing this in C and it worked.
> 
> ex:
> 
> UInt x = 2;
> UInt y = 4;
> UInt z;
> 
> z = x - y;
> 
> Now it would be a -2 except for the fact it's an Unsigned Integer.... thus
> it should be 2.  What I get from my application is 65534, which is roughly
> the maximum value of an int type... am I correct?
> 
> How come it isn't a 2?

Because 2 != -2

Seriously, for 16-bit numbers, 65534 unsigned and -2 in 2's complement 
representation have exactly the same binary bit pattern: 
1111111111111110

"Unsigned" does not mean "treat as signed but ignore the sign" (which 
is apparently what you want). It means, "do not interpret the most 
significicant bit as a sign bit". All values are positive, and 
performing an operation that causes a wraparound produces yet another 
positive value. So:
    2          0000000000000010
  - 4        - 0000000000000100
-----        ------------------
65534          1111111111111110

(Hint: although the binary math is shown above, work it out for 
yourself.)

Interestingly, if you tell the compiler that the values are signed 
instead of unsigned, you get *exactly* the same binary values. (Hint: 
how do you express -2 as a 16-bit 2's complement number? See above.) 
For numbers in 2's complement, math on signed and unsigned numbers is 
identical. The distinction comes into play when you are comparing two 
numbers.

Sorry for being so long-winded (and off-topic :-)

--
Roger Chaplin
<[EMAIL PROTECTED]>

-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palm.com/devzone/mailinglists.html

Reply via email to