Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c why does this print a negative number?

Tags:

c

hex

I was expecting this to print a very large number and that same number -1 but it just prints -1 and -2, why is this?

fprintf(stderr, "%d\n", 0xffffffff);
fprintf(stderr, "%d\n", 0xfffffffe);
like image 533
user105033 Avatar asked Sep 29 '09 13:09

user105033


1 Answers

The %d format is a signed integer (decimal). Integers are stored using two's complement, which means that the high-order bit (8000 0000) indicates, in a manner of speaking, the sign of the value.

Counting down from 3, values are:

0000 0003 = 3
0000 0002 = 2
0000 0001 = 1
0000 0000 = 0
FFFF FFFF = -1
FFFF FFFE = -2

etc.

If you want FFFF FFFF to display as a large positive number, use the %u (unsigned) format.

like image 179
Bob Kaufman Avatar answered Sep 20 '22 16:09

Bob Kaufman