2

I'm new here but I was just wondering what ~0 would be if in the two's complement system, signed integer.

Is it -1 because the flipping of 0 is 1, but if it's signed the answer would be -1? Or is the answer just 1 and just because I'm working with signed numbers doesn't mean that it would be -1?

Z. H.
  • 21
  • 2

2 Answers2

3

0 is a signed int (if you wanted it to be unsigned, you'd write 0U) and therefore ~0 is also a signed int.

If your machine uses a 2's-complement representation, then that will have the value -1. The vast majority of machines -- possibly all the machines you will ever see in your career -- are 2's-complement, but technically speaking, ~0 may invoke undefined behaviour if you use it on a machine which uses 1's-complement representation of signed integers and which also prohibits negative zeros.

Even if it may not matter, it's a good idea to get into the habit of only using unsigned integer types with bitwise operators.

Remember that the bitwise operators perform "the integer promotions" on their operands, which means that signed and unsigned short and char are automatically promoted to int -- not unsigned int (unless it happens that short is the same width as int) -- so an explicit cast to unsigned may be necessary.

rici
  • 234,347
  • 28
  • 237
  • 341
-1

~0 is not the two's complement of zero. It is the bit inversion of 0, which is the same as the one's complement.

If you want the two's complement in C, you will need -0 (note the minus sign) And, -0 would just be 0.

Proof (in eight bit)
zero             - 0b00000000
one'e complement - 0b11111111
Add one          - 0b00000001  (ignoring overflow)
                   -----------
Two's complement - 0b00000000
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • I don't think the OP is saying that `~0` is the two's complement of `0`. OP is asking what the decimal value of `~0` is in a two's complement system. – kaylum Sep 21 '16 at 04:15
  • I have answered that question too. If you frame the two's complement as `-0` then it becomes clearer that it is actually 0. – Rishikesh Raje Sep 21 '16 at 04:36
  • So are you saying that `~0` is the same as `0`? The question is not what the value of `-0` (minus zero) is but what the value of `~0` (bit wise not of zero) is. – kaylum Sep 21 '16 at 04:39