user105033
user105033

Reputation: 19568

c why does this print a negative number?

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);

Upvotes: 6

Views: 3489

Answers (4)

Bob Kaufman
Bob Kaufman

Reputation: 12815

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.

Upvotes: 30

Richard
Richard

Reputation: 1690

The argument "%d" prints the input as a signed integer. As a result, you have discovered the two's complement representation, consider "%u" instead.

Upvotes: 8

Dan Monego
Dan Monego

Reputation: 10087

The first bit on a signed integer is the sign, so the highest number that could be stored is 0xEFFFFFFF.

Upvotes: 3

pavium
pavium

Reputation: 15118

The values you mention are the two's complement representation of -1 and -2

Look up two's complement

Upvotes: 4

Related Questions