This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Five Lines of Code and have Christian Clausen on-line!
See this thread for details.
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

~ Operator :banghead:

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
41 = 101001
~41 = 010110 = -42
i dont understand this...because
when i invert the bits i am getting 22,
can somebody explain me this in detail...

Thank You In Advance
 
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're being confused by the way you've represented decimal 41 in binary as 101001.

Remember that the leftmost binary digit of a signed integer represents the sign, 0 for positive, 1 for negative numbers. So you really need to fill out all the zeros to the left. To keep it simple, let's limit it to 8 bits. So 41 would really look like this in binary, 00101001. Since the leftmost digit is zero, this is a positive integer. (If you used 32 bits you'd of course just have a bunch more zeros to the left. If you actually had a 6-bit integer, 101001 would represent -23.)

The "negate" operator, ~, flips the bits so you get this 11010110. The leftmost digit is 1 so this is a negative integer. To figure out its decimal value, you just use the twos complement to find the positive value and add the minus sign. The twos complement is of course just the negation of the number plus 1, or 00101001 + 1 = 00101010, which is 42 in decimal, or -42 with the minus sign, since you know that 11010110 is negative.
 
See ya later boys, I think I'm in love. Oh wait, she's just a tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic