简体   繁体   中英

Converting from decimal to binary digits upto n bits

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM