Java中将Bin转换为Dec错误结果? [英] Convert Bin to Dec in Java Wrong result ?
本文介绍了Java中将Bin转换为Dec错误结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public double Bin2Dec(String n)
{
double result= 0;
for (int i = n.length() - 1; i >= 0; i--)
{
result += (int)(n.charAt(i)) * luythua(2, n.length() - i-1);
}
return result;
}
public double luythua(int x, int n)
{
if (x == 0)
return 0;
if (n == 0)
return 1;
return x * luythua(x, n - 1);
}
使用该代码,当我调用Bin2Dec("111")时返回343.0(不是7)
大家都帮我解决这个难题吗?谢谢!
With that code, When I call Bin2Dec("111") return 343.0 (not 7)
everyone help me resolves this proplem? thanks !
推荐答案
您需要做的就是从零开始.然后针对字符串中的每个字符:
将结果左移1位
屏蔽掉字符的低位并将其添加到结果中
重复
注意:使用整数值时请勿使用double
.
All you need to do is start with a result value of zero. Then for each character in the string:
shift the result left 1 bit
mask off the low order bit of the character and add it to the result
repeat
Note: do not usedouble
s when working with integer values.
这篇关于Java中将Bin转换为Dec错误结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文