Tell me the direction of the problem.

Given a number. It is required to fill an array by the following principle: [bit number of number] = bit value of a number .

Thank you in advance.

    2 answers 2

    I do not remember which in x86 bit 0 - the older or the younger. For the case "bit 0 - low", i.e. the result will be a binary representation of the number in reverse order:

    #include <stdio.h> int main(int argc, char *argv[]) { int in, r[sizeof(int)*8]; int i; scanf("%d", &in); for(i=0; i < sizeof r/sizeof(int); i++, in >>= 1) r[i] = in & 1; for(i=0; i < sizeof r/sizeof(int); i++) printf("%d", r[i]); putchar('\n'); return 0; } 

    Those. in the loop, select the low order in & 1 and shift the original number to the right.

    • If you want to keep the value of the variable in, you can do a calculation in a loop r [i] = (in >> i) & 1; In terms of the cycle, respectively, remove the conversion in. - skegg
    • Talk about optimization? At weak percents. (for example, microcontrollers), the shift by one bit is one command, and the shift by i is several. - alexlz
    • Well, when we write for microcontrollers, we take into account your comment. - skegg

    I propose such a code. Let a be the same number, let it be of type int.

     int array [sizeof(a)*8]; int i; for (i = 0; i < sizeof(a)*8; i++) array[i]= ((a & (1 << i )) != 0 ) ? 1 : 0; 
    • one
      Well, the value of expressions ((a & (1 << i )) != 0 ) ? 1 : 0 ((a & (1 << i )) != 0 ) ? 1 : 0 and (a & (1 << i )) != 0 in the C language is the same. And, I think, a normal compiler and the code will do the same :) - alexlz
    • I thought about it. Decided to err. But I liked your decision more. Bravo. - skegg