On Fri, 3 Oct 2003 15:51:59 +1000, you wrote:

>Im trying to retrieve the unsigned value of an integer. sounds pretty simple...
>
>[code]
>$i = -86;
>echo "<br>" . sprintf("%d", $i);
>echo "<br>" . sprintf("%u", $i);
>[/code]
>
>produces:
>-86
>4294967198
>
>what i expected:
>-86
>86
>
>Ive searched the archives but most of the messages refer to %s or %d... nothing in 
>regards to %u
>
>can anyone see what im doing wrong?

Uh... first, that's correct behaviour for %u

Second, you're trying to find the absolute value of an integer:

echo (abs(-86));

Third, how to explain the behaviour you're seeing. Um...

Binary numbers are made up of two symbols, right? 0 and 1.

There's no room in a binary computer for a third '-' symbol to denote
negative numbers, so you have to overload one of your existing symbols to
signify "negative".

Ok, lets work with 8-bit numbers to simplify things. An unsigned 8 bit
number can run from 0 to 255:

00000000 = 0
00000001 = 1
[...]
11111110 = 254
11111111 = 255

By convention, a signed 8-bit number sacrifices it's left-most column to
denote negative (1) or positive (0), so it can run from -127 to +127:

11111111 = -127
11111110 = -126
[...]
10000001 = -1
00000000 = 0
00000001 = 1
[...]
01111110 = 126
01111111 = 127

Hope you're with me so far - signed numbers use the left-most column to
store the sign of the number. If the left-most column is 1, the number is
negative.

What you are doing with %u is forcing printf() to treat a signed number with
a leading 1 as if it was an unsigned number. Thus, an unsigned int

10000001 = -1

would be interpreted as

10000001 = 129

This stuff is very basic Computer Science.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to