For this exercise I'm making I want a decimal < 4096 to be written in binary form in an int array.
So for example, 4 would be {0,0,0,0,0,0,0,0,0,1,0,0}. I need this for (nearly) all integers up to 4096, so I've written this piece of code:
for(int k=0; k<4096; k++){
int[] myNumber = { (k / 2048) % 2, (k / 1024) % 2, (k / 512) % 2, (k / 256) % 2, (k / 128) % 2, (k / 64) % 2, (k / 32) % 2, (k / 16) % 2, (k / 8) % 2, (k / 4) % 2, (k / 2) % 2, (k / 1) % 2 }
/* Some processing */
}
This looks kind of ugly, so that's why I'm curious to find out if there is a more elegant way of achieving this?
For the interested reader:
I chose for the array approach of storing the binary numbers, because I need to perform some shifting and addition modulo 2. I'm using an LFSR, and this is my implementation for that:
public class LFSR {
private int[] polynomial;
public LFSR(int[] polynomial) {
this.polynomial = polynomial;
}
public int[] shiftLeft(int[] input) {
int[] result = new int[input.length];
int out = input[0];
result[input.length - 1] = out;
for (int i = input.length - 1; i > 0; i--) {
result[i - 1] = (input[i] + polynomial[i - 1] * out) % 2;
}
return result;
}
}
Any suggestions?