2014-12-02 25 views
0

我正在使用以下代碼在C中創建位圖並啓用一個位。但問題是,當我正在閱讀時,我得到了比預期更高的一位。C位圖給出的值高於預期值

#define BITS_PER_WORD (sizeof(uint32_t) * CHAR_BIT) 
#define WORD_OFFSET(b) ((b)/BITS_PER_WORD) 
#define BIT_OFFSET(b) ((b) % BITS_PER_WORD) 

main() 
{ 
// declarations 
int val = 2; 
init_bits(&bmp); 
set_bit(&bmp,val); 

for (id = 0; id < sizeof(bmp); id++) 
     { 
      if (bmp & (1 << id)) 
      { 
       trace(debug, "bit:%x", bmp,); 
      } 
     } 
} 

init_bits(uint32_t *words) { 
    (void)memset((void*)words, 0, sizeof(uint32_t)); 
} 

set_bit(uint32_t *words, int n) { 
     words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n)); 
} 

所以,例如,如果我執行SET_BIT(& BMP,2),那麼我在十六進制得到(而不是2)4和SET_BIT 10(而不是8)所在地(& BMP,4)等。

任何幫助,非常感謝!

+0

'C bitmap giving ....'並標記爲'C++'?刪除標籤。 – 2014-12-02 14:16:02

回答

5

我認爲你的期望是錯誤的。通常的方式工作是:

  • SET_BIT(0) - > 1
  • SET_BIT(1) - > 2
  • SET_BIT(2) - > 4
  • SET_BIT(3) - > 8
  • SET_BIT(4) - > 16(0×10)
  • SET_BIT(5) - > 32(0×20)
  • SET_BIT(6) - > 64(0×40)
  • SET_BIT(7) - > 128( 0x80)

請注意,這正是基數2指數函數的數值的值。

如果您需要其他約定,則必須相應地添加或減少。