1

I am following this tutorial: https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm https://www.tutorialspoint.com/cprogramming/c_operators.htm

I am confused how A which starts out as: A = 0011 1100 (60 in decimal) can become -61 when all the bits are flipped with the ~ operator.

I understand that ~A will become: 1100 0011. From my calculations, this binary number 1100 0011 equals 195 in decimal. However the answer is -61 in base ten according to the c programming language and the tutorial.

Could someone please help me understand?

Thank-you for reading this question.

user3808269
  • 1,321
  • 3
  • 21
  • 40

1 Answers1

1

When you flip the bits of a signed positive value, you flip the higher bit as well (on any type).

So when you print the value, you get a negative value.

With an unsigned 8-bit type, you'll get what you want:

#include <stdio.h>

int main()
{
   int x = 60;
   printf("%d\n",~x);
   char y = x;
   printf("%d\n",~y);
   unsigned char z = x;
   printf("%u\n",(unsigned char)~z);

   return 0;
}

result:

-61
-61
195

for integer & char, you get -61, but if you use an unsigned char, you get 195, higher bit is used for value not for sign.

1100 0011 is 195 when considering all bits having the same meaning (unsigned).

1100 0011 signed is 100 0011=64+2+1=67 - 2^7=128 = -61

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Awesome. But can you explain how I would get this by hand? Like how does 1100 0011 become -61 when it seems to mean 195? That is interesting how the unsigned char becomes 195 when flipped just as I get when I flip the bits by hand and then figure out the base ten value based on that. :) – user3808269 Dec 21 '16 at 22:46
  • @user3870315 you also got -61 by hand, just interpret those bits as an 8bit signed integer. – harold Dec 21 '16 at 23:31
  • I am not sure how to do that @harold. 0_o – user3808269 Dec 21 '16 at 23:54
  • 1
    @user3870315 almost the same as usual, but use a negative weight for the top bit, so -128 for 8 bits, you'd get -128 + 64 + 2 + 1 – harold Dec 22 '16 at 00:03
  • That is an excellent answer @harold. Thank-you for chiming in. :)))))) – user3808269 Dec 22 '16 at 00:17