Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fast way to count ~X where X is any number (even -ve)

 
kishor kotecha
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was facing a problem in converting not of a number i.e. ~X.
Though I know the method ...
1. find the binary of the number and
2. revese all the bits.
It can be done but is a SLOW process when you are short of time in exam. for eg. what is ~4569? It will take time. find binary of 4569 will take time manually in exam. I found a VERY FAST method somewhere on net.
fast method ~x = -x -1
i.e. ~4569 = -4569 -1 = -4570.
or ~-1234 = --1234 -1 = 1233.
simple isnt it?
I thought this might be usefule to many in exam and hence posted on saloon. Suggestions welcome.
 
Sathvathsan Sampath
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reasoning behind this formula is as follows:
1) Complement of a number is basically inverting the bits i.e. 0 ->1 and vice versa.
So, when we put a '-' sign in front of a no, then internally, this is calculated in 2s complement form:- first invert the bits (i.e. 1's complement) and then add 1 to this complemented number.
2) Since, we are just intrested in the inverted bits, subtracting 1 from the above inverted number will st away give the 1s complement form of the original no.
In short,
for -2:
2 -> 0010
-2 -> in 2s complement is: 1's complement + 1 i.e
1s complement of 2 = ivert bits of 0010 = 1101
now adding 1 gives: 1110 which is the 2s complement form of -2
Hence, doing exactly the opposite of last step would give as the desired quick answer for getting ~2.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic