2013-02-07 46 views
1

我有一个变量unsigned int x = 0b0011我怎样才能使它成为无符号整数数组,如y[0]=0 ; y[1]=0; y[2]=1; y[3]=1;c中的整数数组中的二进制整数

+0

这是一个int'0b0011'吗? –

+0

你是否总是知道二进制表示中的位数或是否是任意的? –

+0

Noor:如果有必要,我可以将变量定义为'int'。 @Jordan Kaye:我只需要从GPIO输出二进制值,我需要知道整数值作为二进制文件。所以我可以说这不是任意的 – sven

回答

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; 
}