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

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

Joined: Oct 13, 2005
Posts: 46378
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:
subject: Negative binary to decimal problem
It's not a secret anymore!