Hi,
If you look at the binary()
function, it’s returning the binary representation as a String
.
In order to get a portion of a String
in Java, use the subtring()
method which takes to indices and return the corresponding substring.
You can write a method to cut the first n characters of a String :
/*
Cut the first n characters from a source String
*/
String trimCharacters(String source, int n) {
return source.substring(n, source.length());
}
That you can use like this :
println(trimCharacters(binary(a), 20));
Note that it’s more coherent to use the pre defined print()
and println()
functions in Processing rather than classic Java System.out.print...
If you want to remove all the zeros, you need to compute the maximum exponent p
where 2 to the power of p
is less than or equal to your number a
, which represents the length of your binary number without the zeros.
You can use another function to do this :
/*
Return the highest exponent p where 2**p < n
*/
int getHighestExponentPowerOfTwo(int n) {
int p = 0;
while (pow(2, p) < n) p++;
return p;
}
It increase a value p
and stops when 2**p > n
.
Since the binary()
function returns the 32 bit
representation of the value, we need to cut 32 - binary size of a
zeros from the string.
So finally it goes like this :
// We add one because the smaller power start with 0
int binaryLength = getHighestExponentPowerOfTwo(a) + 1;
int zerosToTrim = 32 - binaryLength;
println(trimCharacters(binary(a), zerosToTrim));
And you get :
0
1
10
011
100
0101
0110
0111
1000
01001
01010
01011
01100
01101
01110
01111
10000
010001
...
Note, this is a bit over complicated but it’s a nice exercise and it introduce you to functions if you are not used to
A better way would be to use the indexOf()
method to get the first position of a 1
in the binary representation and cut from that index. I let you do this part!