Ruchi
November 20, 2019, 6:59am
1
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
hamoid
November 20, 2019, 10:53am
2
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
Ruchi
November 23, 2019, 5:55am
3
1st & 3rd method is bit intimidating lol. Could you provide some reference for understanding this sort of expression.Thanks
1 Like
kll
November 23, 2019, 8:04am
4
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
hamoid
November 23, 2019, 9:21am
5
2 Likes
glv
November 23, 2019, 9:34am
6
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