So I was working on a simple binary to decimal script and an error occurred where there is a possible loss of precision when multiplying by a power. This is the code block in question, all it does is times the 1’s and 0’s in binary by 2 to the power of the strings length minus how many iterations the loop has gone through. It then add that result to z, and repeats.
public int decimal(String x){
int z=0;
for(int a=0;a<x.length();a++){
z=z+Integer.parseInt(x.substring(a,a+1))*Math.pow(2,x.length()-a);
}
return z;
}
Replace:
with:
And you’ll be fine as long as integers do not overflow. You are unnecessarily using
doubles, not to mentionMath.powisn’t the most effective and straightforward way to compute the power of 2.BTW is the whole point of
decimal()method is to parse binary string? If so, try this:Yes, that’s it.