Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output of Bitwise ~ operator ?

 
Anto Telvin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
i have the following code
int a=3;
int b=~a;

but if we are calculating it a=0011 in binary after inverting we get 1100 to decimal it is 12 .but i am getting as output -4 .can anyone tell why the output is like that ?

thanks
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hope you know that In Java, negative values are stored in two's complement format.

and
int a = 3 does not mean a = 0011 in binary because int is 32 bit in java
therfore
a is 00000000 00000000 00000000 00000011 in binary
now taking ~a ==> 11111111 11111111 11111111 11111100 which is a negative value . We will take two`s compliment now. Which comes out to be 4

Hence answer is -4.
 
Anto Telvin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks i got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic