# simple bitwise complement ~ question, help

sarim raza

Ranch Hand

Posts: 232

Anubala shrivastava

Greenhorn

Posts: 9

posted 15 years ago

- 0

~ 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

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

Amit Tyagi

Ranch Hand

Posts: 52

posted 15 years ago

- 0

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

hope this will help you.....

Bye

Amit

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

hope this will help you.....

Bye

Amit

It is sorta covered in the JavaRanch Style Guide. |