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 Negative binary to decimal problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Negative binary to decimal problem " Watch "Negative binary to decimal problem " New topic
Author

Negative binary to decimal problem

G. Graz
Ranch Hand

Joined: Oct 23, 2006
Posts: 30
I have an application that I am trying to convert a negative binary number to the negative decimal number. The method that I have below doing this is BTD. I can get the positive numbers to compute correctly but a negative binary number to negative decimal number I can not ? Any suggestions would be of great help !! Thank you!!

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Difficult to see exactly what is going on.

Why are you using 16 for your length of String and a 32-bit representation? That is likely to confuse you.
The multiple return statements are bad form, and are also causing the while loops to terminate prematurely.
The names of the methods are confusing; it is not easy to read DTB and BTD.
In the BTD method you have an if, and you think the two statements after that will be executed if the condition is true. They won't. Because you have omitted the {} after the if, only one will be included in the if block and the statement with the unsigned right shift will execute regardless.

Suggest you implement a power method; I wrote a tongue-in-cheek power function in another language here; Ulf Dittmer correctly interpreted it in Java. Then you can add -power(2, 31) if you reach the end of the String, and iterate along the characters from 1 [for (int i = 1; i<bin.length(); i++)]

Suggest you don't call the class Number; there already is a java.lang.Number class and creating a class with the same name may cause severe confusion weeks later.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Negative binary to decimal problem