Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary to decimal  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
3 bit value is---->11
for finding -3 value(flip+add 1)
fliping gives----->1111 1111 1111 1111 1111 1111 1111 1111 1100
add 1 gives----> 1111 1111 1111 1111 1111 1111 1111 1111 1101(this is the result of -3 bit representation)
But when i convert the previous bit representation back to decimal as 1*2^0+0*2^1+1*2^2--->-5 (why it is not giving -3 value)
Then how come the bit representation is the result of -3.
Am i making any sense here?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To convert it back to decimal, do the process again.

Flip the bits and add 1.
 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

The way you're looking at it is not correct. If you look at it that way, that value wouldn't even be -5, because you have to count all 1's that correspond to the left most bits. Then, it would be:

1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + *2^4 + *2^5 + *2^6 ... (a very large number)

Here's how you should evaluate the number (suppose 8 bits in the representation):

0000 0011 (base 2) = 3 (base 10)

We want -3, so we compute the two's complemente (as you suggested). We invert the bits:

1111 1100

Now, we add 1:

1111 1101

The representation above is -3 (in two's complement). How do we know that? We first note that the most significant bit is 1.

1....... (ok, we have a negative number)

Since we know we have a negative number, its value is the corresponding positive value. So, we invert the bits back:

0000 0010

And we add one back:

0000 0011

Now, we have 3 and we know that the negative number is -3.

To look at in a way closer to what you want, you would have to do the math computing the most significant bit as a negative value. For example, suppose that we our two's complement of three:

1111 1101

We can use the power of twos in the following way:

1111 1101 = -1*2^7 + 1*2^6 + 1*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0
1111 1101 = -128 + 64 + 32 + 16 + 8 + 4 + 0 + 1
1111 1101 = -3

Is that clear now?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!