• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Bitwise complement operator

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

In K & B book for SCJP 1.4, on page 175, the bitwise complement (~) operator is explained:



After line 2 the value of x is -6.

In bit representation 5 is:
0000 0000 0000 0000 0000 0000 0000 0101

the flip-the-bits operator converts it to:
1111 1111 1111 1111 1111 1111 1111 1010

How do I convert the converted bit value back to -6?
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
~x = -x - 1
 
d jones
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Keith,

Is that a rule which I can apply unconditionally all of the time?
 
Keith Lynn
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, in all cases ~x = -x - 1.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int x = 5
bit pattern is 00000000 00000000 00000000 00000101
~x pattern is 11111111 11111111 11111111 11111010

Now since the MSB(most significant bit) is 1 we know its a -ve number. To get the actual value of the -ve number take 2's complement of the number

00000000 00000000 00000000 00000101
+ 1
-----------------------------------
00000000 00000000 00000000 00000110
which is nothing but 6
so ~x = -6

Regards,
Chaitra
 
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and of course this is only a 1.4 topic, not 5.0
 
Thank you my well lotioned goddess! Here, have my favorite tiny ad!
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic