#include <stdio.h>
#include <stdlib.h>
/*Integer x be converted to binary format.
*Return binary array instance of x.
*-1 act as array terminator.
*/
int*
toBin(int x) {
int *ret, c = 0, i, j;
ret = malloc(sizeof *ret * 32);
/*Shift bits to left one by one until x is zero.*/
/*Store each bit to array*/
while (x > 0) {
if ( (x & 1) == 1)
ret[c] = 1;
else
ret[c] = 0;
x >>= 1; c++;
}
/*Reverse array swapping values*/
for (j = 0;j < c;j++) {
for (i = 0;(i+1) < (c-j);i++) {
ret[i] ^= ret[i+1];
ret[i+1] ^= ret[i];
ret[i] ^= ret[i+1];
}
}
ret[c] = -1; //TODO better array terminator
return ret;
}
int
main (void) {
int i, c = 0, *arr;
for (i = 1;i <= 170;i++) {
arr = toBin(i);
printf("%d = ", i);
while (arr[c] != -1) {
printf("%d",arr[c]);
c++;
}
c = 0;
printf("\n");
free(arr);
}
return EXIT_SUCCESS;
}