File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Binary to decimal Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Binary to decimal" Watch "Binary to decimal" New topic
Author

Binary to decimal

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 465
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

Joined: Feb 07, 2005
Posts: 2341
To convert it back to decimal, do the process again.

Flip the bits and add 1.
Leandro Melo
Ranch Hand

Joined: Mar 27, 2004
Posts: 401
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?


Leandro Melo <br />SCJP 1.4, SCWCD 1.4<br /><a href="http://www.pazbrasil.org/" target="_blank" rel="nofollow">http://www.pazbrasil.org/</a>
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Binary to decimal
 
Similar Threads
Shifting Rules?? (+/-SRS,+/-LS+/-URS)
Right Shift Operator (>>)
Shift operators!
problem with bit shift >>>.
i don't get shift operators!!!!