• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Negative binary to decimal problem

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!!

 
Marshal
Posts: 80760
487
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic