Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Bitwise complement operator

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have an int x = 5;
0000 0000 0000 0000 0000 0000 0000 0101
~x
converts to:
1111 1111 1111 1111 1111 1111 1111 1010
Now, x = -6 WHY???
I know that the 32th digit represents the -ve sign. How to compute the number "6"?
Thanks for help.
Andrew
 
Sheriff
Posts: 15758
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this thread out: http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=001584
 
Andrew Parker
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I understand it now.
1111 1111 1111 1111 1111 1111 1111 1010
=
- (2^32) + (2^31....3) + (2^1) = - 6
Thanks
Andrew
 
Junilu Lacar
Sheriff
Posts: 15758
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Now you got me worried that you don't understand...
All you need to do is get the two's complement:
1. complement the number
2. add 1
If you start out with a negative number, you will get its positive and vice versa.
The way you showed it would be way too long unless you've memorized all the powers of 2 and can add really fast. I'm not even sure it'll give you the right result for all, if any, numbers.
 
A tiny monkey bit me and I got tiny ads:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic