Home > Enterprise >  Bitwise operator ~ goes wrong [closed]
Bitwise operator ~ goes wrong [closed]

Time:09-27

I'm learning the bitwise operators in C. When I calculate the outcome of ~4 I get 11, also when I calculate it on a website I get the same outcome. But my compiler gives me the wrong result, everytime when I compile I get 5. I think my compiler settings are wrong. I searched on the internet for the problem but didn't find anything.

What can I do to solve this?

int x = ~4;
    printf("%d\n", x);

CodePudding user response:

You have not taken into account that data types have a certain size which is fixed independently from its content.

On most modern systems, an int has 32 bits. This means your 4 is represented as

00000000 00000000 00000000 00000100

and when you do ~ you get

11111111 11111111 11111111 11111011.

As int is a signed data type and (on most modern systems) two's complement is used for representing negative values, this is shown as -5.

CodePudding user response:

The correct answer should be -5.

 4 = 00000000 00000000 00000000 00000100
~4 = 11111111 11111111 11111111 11111011

This is the binary representation of -5 using a 32-bit signed integer. For signed integers, ~x=-x-1.

CodePudding user response:

Whatever you do and whereever you try it, you will get a negative number as result.

4 is represented as 0 0 0 ... 1 0 0. Bit-negation will look like: 1 1 1 1 ... 1 0 1 1. This will be a small negative number. Now, depending on the representation of integers, it can vary, but it will be negative. From 6.2.6.2 Integer types:

For signed integer types, the bits of the object representation shall be divided into three groups: value bits, padding bits, and the sign bit. There need not be any padding bits; there shall be exactly one sign bit.

CodePudding user response:

This might be the easiest way to show you:

#include <stdio.h>
  
int main() {
    printf("%o\n", 4);
    printf("%o %d\n", ~4, ~4);
    printf("%o %d\n", 4   ~4, 4   ~4);
    return 0;
}

will display:

4
37777777773 -5
37777777777 -1

If you add 4 to the last octet 3 of the octal encoding you get 7 hence complement was applied as as expected. Why is the 2nd number looking so strange, that's because it's encoded as twos compliment.

  • Related