Converting from decimal to binary digits upto n bits

Viewed 125

I am converting decimal numbers to n binary bits, then separate it into n binary bits and then assign it to x by x grid.

For example:- 325 -> 101000101 -> 1,0,1,0,0,0,1,0,1

I have written the following code, please help me figure out what algorithm shall I use for this task. Thanks!

int binary_num[100];
int separate_num[100];

    for (int i = 0; i<pow(2,4); i++) {
        int j = 0;
        int n = i;
        while(n>0) {
            binary_num[j] = n%2;
            j++;
            n /= 2;
        }
        for (int k = j-1; j>=0; j--) {
            int h = 0;
            separate_num[h] = binary_num[k];
            h++;
        }

    }


return 0;
1 Answers

Use bitset to find the required number of bits and you can store it in array then print in grid

Related