# simple bitwise complement ~ question, help

sarim raza
Ranch Hand
Posts: 232
can someone explain the outcome of the following
~4
using bytes or some other formula
is this formula valid in these circumstances?
1. change sign and subtract one ?
thanks

Anubala shrivastava
Greenhorn
Posts: 9
~ is a bitwise inversion operator .It just invert bytes from 0 to 1.
4 can be written as 0000 0000 0000 00100 in bits presentation
and ~4 will be------1111 1111 1111 11011 this is just inversion of bytes.since higher order bit is 1 it means this must be negative number,ans accordin to java negative no represent in two's complement.In order to see magnitude of two's complements no just invert bit and add 1 bit in lower order bit.
So it wiil be 0000 0000 0000 00100
+ 1
----------------------
= 0000 0000 0000 00101
When you convert it into decimal no it will be 5
so ~4 will be -5.
If I m wrong please anybody explain it.
--Anubala

Rob Levo
Ranch Hand
Posts: 167
Correct

Amit Tyagi
Ranch Hand
Posts: 52
hI sarim ,
above things are exactly correct.
But u can follow this thumb rule also as you won't be getting time to calculate all this.
~x = -(x)-1
here x is a signed number means ..if
x =4 then -(4)-1 = -5
x =-4 then -(-4)-1 = 3
x = 0 then -(0)-1 = -1