NameSake
NameSake

Reputation: 53

tilde operator query in C working differently

I came across this question. What is the output of this C code?

#include <stdio.h>

    int main()
    {
        unsigned int a = 10;
        a = ~a;
        printf("%d\n", a);
    }

I know what tilde operator do, now 10 can be represented as 1010 in binary, and if i bitwise not it, i get 0101, so i do not understand the output -11. Can anyone explain?

Upvotes: 2

Views: 288

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

The bitwise negation will not result in 0101. Note that an int contains at least 16 bits. So, for 16 bits, it will generate:

 a = 0000 0000  0000 1010
~a = 1111 1111  1111 0101

So we expect to see a large number (with 16 bits that would be 65'525), but you use %d as format specifier. This means you interpret the integer as a signed integer. Now signed integers use the two-complement representation [wiki]. This means that every integers where the highest bit is set, is negative, and furthermore that in that case the value is equal to -1-(~x), so -11. In case the specifier was %u, then the format would be an unsigned integer.

EDIT: like @R. says, %d is only well defined for unsigned integers, if these are in the range of the signed integers as well, outside it depends on the implementation.

Upvotes: 4

Stephan Lechner
Stephan Lechner

Reputation: 35154

It's undefined behaviour, since "%d" is for signed integers; for unsigned ones, use "%u".

Otherwise, note that negative values are often represented as a two's complement; So -a == (~a)+1, or the other way round: (~a) == -a -1. Hence, (~10) is the same as -10-1, which is -11.

Upvotes: 3

Galen
Galen

Reputation: 1307

The format specifier for an unsigned decimal integer is %u. %d is for a signed decimal integer.

printf("%d\n", a) is interpreting a as a signed int. You want printf("%u\n", a).

Upvotes: 1

Related Questions