Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

16bit binary to decimal problem

 
G. Graz
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to convert a string binary value to it's decimal value. the code I have below keeps on generating a zero (0) every time I run the application? I can go through my logic on paper and get the correct value, but I am at the end of my rope on why my code is not generating the correct result. Any suggestions would be of great help! Thank you in advance !!!

Here is my code:

private int BTD(int n, String bin)
{
int result = 0;

for (int i=0; i<bin.length(); i++)
{
result = (result * 2) + (bin.charAt(i)-'0');
}
return result;
}
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg,

In the future, please post your code using the CODE UBB tags to make it more readable.

Not sure why you keep getting 0 as the result. I ran your code as is and get the expected results. How are you calling the code and checking the result?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How exactly are you calling your method and how are you dealing with the result returned from the method? Note that the argument 'n' is never used in the method, so you could just as well remove it.

[ April 28, 2008: Message edited by: Jesper Young ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer.parseInt("100110100111", 2) should work.
 
G. Graz
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for all the help! I will make sure that future posts are done in the UBB format. The program connects to a user IO class which takes user binary input as a string and should convert it over to a decimal number. My teacher did not give us access to the .Java file for IO though. As long as my logic is correct , I think I will be ok because I know that my end of the application is correct. Thank you again for all the help!!

Greg
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic