File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes 16bit 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 "16bit binary to decimal problem" Watch "16bit binary to decimal problem" New topic

16bit binary to decimal problem

G. Graz
Ranch Hand

Joined: Oct 23, 2006
Posts: 30
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

Joined: Mar 22, 2008
Posts: 265


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?

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

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 ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Integer.parseInt("100110100111", 2) should work.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
G. Graz
Ranch Hand

Joined: Oct 23, 2006
Posts: 30
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!!

I agree. Here's the link:
subject: 16bit binary to decimal problem
It's not a secret anymore!