6

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

4 Answers 4

30

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.

6
  • oh, whats the % for long? or unsigned?
    – user105033
    Commented Sep 29, 2009 at 13:14
  • %u - just added to the response :) Commented Sep 29, 2009 at 13:15
  • 3
    int is %d, unsigned is %u, long int is %ld, long unsigned is %lu Commented Sep 29, 2009 at 13:16
  • 2
    no, the %d means signed decimal, a %u would be unsigned decimal.
    – pavium
    Commented Sep 29, 2009 at 13:16
  • the % just indicates that "something" is going to get put there. For example %.02f is perfectly legit and will print a floating point with 2 digits after the decimal point and if there are no post decimal point digits will print 2 0s.
    – Goz
    Commented Sep 29, 2009 at 13:17
8

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

4

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

Look up two's complement

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.