# Char to int producing different result

``````String bin ="100";
char bit;
float sum;

void setup(){
size(500,200);
noLoop();
sum=0;
}

void draw(){
background(0);
for(int i=0;i<bin.length();i++){
bit = bin.charAt(bin.length()-1-i);
//println(bit);
sum+= parseInt(bit) * pow(2,i);
println(sum);

}
}
``````

Console:
48.0
144.0
340.0

Doing binary to decimal conversion but the parseInt is converting characters to their corresponding ascii values & not to the same number.

1 Like

Here 4 different ways to fix it:

``````sum += bit == '1' ? pow(2, i) : 0;

sum += parseInt("" + bit, 2) * pow(2, i);

sum += bit == '1' ? (1 << i) : 0;

sum += parseInt("" + bit, 2) << i;
``````

`parseInt()` accepts a second argument to specify the base, for binary it’s 2. But the first argument must be a string, not a char.

Also this is the shortest:

``````println(Integer.parseInt("1001", 2));
`````` 4 Likes

1st & 3rd method is bit intimidating lol. Could you provide some reference for understanding this sort of expression.Thanks

1 Like

best: play with it

``````// Java Ternary Operator //The ? : operator in Java as a style of IF
float a = 3, b = 7, max;

if (a > b) {
max = a;
} else {
max = b;
}

println("if",a, b, max);

max = (a > b) ? a : b;

println("? ",a, b, max);

println("a > b", (a > b) );
println("a > b", (a > b) ? 1 : 0 );

``````

it is just a writing style for the IF

1 Like
2 Likes

Hello,

``````String bin ="10001010";
char bit = 0;
float sum = 0;

println(bin.length());

for(int i=0;i<bin.length();i++)
{
bit = bin.charAt(bin.length()-1-i);
sum += bit == '1' ? pow(2, i) : 0;
//sum += parseInt("" + bit, 2) * pow(2, i);
//sum += bit == '1' ? (1 << i) : 0;
//sum += parseInt("" + bit, 2) << i;
println(i, bit, sum);
}
``````

Content of loop courtesy of: 1 Like