The trick with looking at the bits of a number n
is to bitwise and with 1 to get the least significant bit then shift right by one bit and then bitwise and with 1 again to get the bit at the second position and so on.
n>>1 & 0x1
Now to store it in an array you should notice that the least significant bit should go in the last element of the array, so if the array a
is of size is 10. The least significant bit should be in a[9]
Combining these two you will count the array index from the last position to zero and shift your number to get the bit at that position. Now what you store in the array is not 0 and 1 but the character '0' and character '1'. You can convert the number 0 to character 0 by adding it to '0' and the number 1 by adding 1 to '0'.
Combining all the above ideas you get the code below.
void int2bin(int n, char* b, int sz) {
for (int p=sz-1; p>=0; p--,n>>=1) {
b[p] = '0' + (n & 0x1);
}
}
int main(int argc, char**argv){
char a[10]={'0'};
int2bin(atoi(argv[1]),a,sizeof(a));
for (int i=0;i<sizeof(a);++i)
printf("%c",a[i]);
return 0;
}
Just keep in mind that with array size of 10 the maximum number you can represent in binary is 2^10 - 1 = 1023. If you also consider negative numbers then the maximum in 2^9 -1 =511 and the minimum -512