c中的二进制整数到整数数组

时间:2013-02-07 14:23:29

标签: c arrays integer

我有一个变量unsigned int x = 0b0011如何将它变成无符号整数数组,如y[0]=0 ; y[1]=0; y[2]=1; y[3]=1;

1 个答案:

答案 0 :(得分:4)

移位和按位操作。

unsigned x = 0b0011; // yap this is a GNU extension, it doesn't always work even with GCC

const size_t intsize = sizeof(x) * CHAR_BIT; // go go indepency-of-sizeof(int)!

unsigned bits[intsize]; // that's why we love constexprs

int i, j;
for (i = intsize - 1, j = 0; i >= 0; i--, j++) { // and the comma operator too
    bits[j] = (x >> i) & 0x1;
}