2013-02-07 50 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; 
}