user3020666
user3020666

Reputation: 25

Confusion with output of negation operator in Java

byte x=3;
x=(byte)~x;
System.out.println(x);

I was confused between the output being 4 or 0 but the output is coming to be -4. How is that ??

Upvotes: 1

Views: 4764

Answers (5)

Achintya Jha
Achintya Jha

Reputation: 12843

~ is reversing a Bit operator.

Bit reversal consists of reversing the value of a bit. If the box contains 1, you can reverse it to 0. If it contains 0, you can reverse it to 1. To support this operation, the Java language provides the bitwise negation operator represented with the ~ symbol.

3   --> 00000011

~3  --> 11111100

As it's a 2's complement number, the first bit being one means that it's a negative number.

11111100=-4

To verify see below:

00000011 <- reversing 
+      1<- adding 1
00000100 =4

Upvotes: 0

kshirish
kshirish

Reputation: 1549

It's simple !! ~a = -a - 1

Since the value of a = 3, the answer must be -4. You can check with other values too.

Upvotes: 2

Maroun
Maroun

Reputation: 95968

See the official docs:

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

What is 3 in binary? It's 0000 0011.

What's ~3? It's 11111100, which is -4 (Two's complement).

Note, ~ is not an negation, it's an operator.

Upvotes: 2

Woot4Moo
Woot4Moo

Reputation: 24316

bit 3 = 0000 0011
x = 3
~x = 1111 1100

the ~ is the bitwise not. So when the first value in the bit string is a 1 it is a negative

Upvotes: 0

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

On a byte 3 is represented as 00000011. Then ~3 is 11111100 which is a negative number (starts with 1).

Upvotes: 2

Related Questions