I think, println is a complex function that does a lot of work behind the scenes to be able to work with all different kinds of input (data types)
You have to make yourself familiar with what binary numbers are.
4 decimal is: 100 binary etc.
because in our system in every “slot” we count to 9, in binary to 1.
Here is the list
0:
1: 1
2: 10
3: 11
4: 100
5: 101
6: 110
7: 111
8: 1000
9: 1001
10: 1010
11: 1011
12: 1100
13: 1101
14: 1110
15: 1111
16: 10000
17: 10001
18: 10010
19: 10011
20: 10100
21: 10101
22: 10110
23: 10111
24: 11000
25: 11001
26: 11010
27: 11011
28: 11100
29: 11101
30: 11110
31: 11111
32: 100000
(it doesn’t really work for 0, should give 0)
Now, let’s look at the function.
first half it builds dual, 2nd half it just copies dual into dual1 backwards.
Which is a bit unnecessary, see here:
String DualZahl(int a) {
String dual = "";
int i = a;
while (i > 0) {
if (i % 2 !=0) {
dual = "1" + dual ;
} else {
dual = "0" + dual ;
}
i /= 2;
}
return dual;
}
void setup() {
for (int i=0; i <=32; i++)
println (i + ": " + DualZahl(i) );
//println(DualZahl(2));
}
Anyway. The 1st half loops over the input a (or i, it’s not necessary to copy a to i).
String DualZahl(int i) { // renamed to i, deleted a
if (i==0)
return "0"; // result for 0: 0
String dual = "";
while (i > 0) {
if (i % 2 != 0) {
dual = "1" + dual ; // appending 1 on the LEFT
} else {
dual = "0" + dual ; // appending 0 on the LEFT
}
i /= 2;
}
return dual;
}
void setup() {
for (int i=0; i <=32; i++)
println (i + ": " + DualZahl(i) );
//println(DualZahl(2));
}
It checks if the remainder (% 2) is != 0 (it can be only 1 then).
If so, we put 1 into dual
(this is on the very right of dual!). It is not even, so the very right slot of the result number must be 1.
We split i by 2: i /= 2; but this an integer division so for example i = 15 / 2 gives 7 and not 7.5.
Now we do the same for the next number. It’s in a while loop so this goes on until i is 0.
I don’t get fully myself.
See how the numbers build up:
for 15:
15 1
7 11
3 111
1 1111
result
15: 1111
for 16:
16 0
8 00
4 000
2 0000
1 10000
result
16: 10000
Chrisir