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.
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.
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.
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;
((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 :) - alexlzSource: https://ru.stackoverflow.com/questions/53658/
All Articles