[英]binary to decimal using CharAt( ) and length( )
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() 我已经编写了将二进制转换为十进制的程序,但是我想知道如何在不使用Math.pow()且仅使用charAt()和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
. 是的,您可以(并且应该)不使用
Math.pow
进行转换。
The following code adds the nth power of 2 to j
: 以下代码将2的n次幂加到
j
:
j += 1 << n;
But I recommend the answer by Jim Rhodes, because it is a simpler solution. 但我建议吉姆·罗德斯(Jim Rhodes)给出答案,因为这是一个更简单的解决方案。 You do not need to raise 2 to various powers;
您无需将2提升至各种异能。 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. 例如,二进制的
111
等于十进制数7,但是如果我再写一个数字,如1110
,则该值等于2 * 7,即十进制表示法14。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.