Ive written a program for converting binary to decimal, however I was wondering how can I do it without using Math.pow ( ) and by only using methods charAt ( ) and length()
thank you,, any help would be appreciated
public class BinaryToDecimal{
public static void main(String[] args){
String binaryString = args[0];
int decimalValue;
int length = binaryString.length();
double j = 0;
for (int i=0; i< binaryString.length(); i++){
if (binaryString.charAt(i)== '1'){
j = j+ Math.pow(2, binaryString.length() - 1 - i);
}
}
decimalValue = (int) j;
System.out.println(decimalValue);
}
}
You can try this:
int j = 0;
for (int i=0; i< binaryString.length(); i++)
{
j <<= 1;
if (binaryString.charAt(i)== '1')
{
++j;
}
}
Yes, you can (and should) do the conversions without using Math.pow
.
The following code adds the nth power of 2 to j
:
j += 1 << n;
But I recommend the answer by Jim Rhodes, because it is a simpler solution. You do not need to raise 2 to various powers; all you really need to know is that every time you write an extra digit on the right-hand end of a binary number, the value of the previous digits is doubled. For example, 111
in binary equals the decimal number 7, but if I write one more digit, like so, 1110
, then the value becomes equal to 2*7, that is, 14 in decimal notation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.