Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tilde operator query in C working differently

Tags:

c

operators

tilde

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?

like image 567
NameSake Avatar asked Dec 07 '25 09:12

NameSake


2 Answers

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.

like image 98
Willem Van Onsem Avatar answered Dec 08 '25 22:12

Willem Van Onsem


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.

like image 20
Stephan Lechner Avatar answered Dec 08 '25 22:12

Stephan Lechner