Reputation: 31
I need to write a program that can convert bits into decimal. Whenever I enter a bit, it only outputs 0.0. I cannot figure out why. I know it's incredibly simple but I am just not seeing it. Any help would be appreciated.
import java.lang.Math;
import java.util.Scanner;
public class Lab1 {
static double number = 0;
public static double toDec(String num) {
char[] charArray = num.toCharArray();
for(int i = 0; i<charArray.length;i++) {
if(charArray[i] == 1) {
number = Math.pow(2, charArray.length-i);
}
}
return number;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int bit;
String bitString;
System.out.println("Please enter a bit");
bit = keyboard.nextInt();
bitString = Integer.toString(bit);
System.out.println(toDec(bitString));
}
}
Upvotes: 1
Views: 3702
Reputation: 31215
Integer#parseInt(String str, int radix) does the job :
public static Integer toDec(String num) {
return Integer.parseInt(num, 2);
}
Upvotes: 1
Reputation: 1787
So if you want to take the String "110011" which is 51. For big-endian you are going to have to determine how many bits to process. So if you read the string and it is 6 digits long then you know the first bit has to be shifted 6 places to the left.
int l = 6;
long value = 0;
for( int i = 0; i < l; i++ )
{
int bit = ( charArray[i] == "1" ) ? 1 : 0;
l = l + ( bit << l-i );
}
For float you would basically have to build an interpreter to decode the bits based on however the float is represented in binary.
Upvotes: 0
Reputation: 178243
You have compared charArray[i]
to 1
, but you're comparing apples to oranges, specifically, a char
to an int
.
Compare to the char '1'
instead.
if(charArray[i] == '1') {
Also, you can make number
a local variable in toDec
; it doesn't need to exist outside that method.
In addition, this will only work if one bit is set. Right now you are working with one bitonly, but if you want to modify this to work with multiple bits, another changes is needed.
You overwrite number
each time toDec
is called and the condition is true
. You will probably want to add to number
with +=
instead of overwriting the previous value with =
.
Upvotes: 6