在32位系统中,存储一位整型(int)数需要4个字节(4B),如果开辟一个空间,把其中的某个位1,就从原来的32b减少到1b,大大节省了空间。

原理

字符数组entry是存储位的数组,我们把数字N存到entry中,则

把第N位置1:entry[nBits/8] = entry[nBits/8] | (1 << (nBits%8) )

检验第N位是否为1:entry[nBits/8] & (1 << (nBits%8)

图示

位操作——整数用位存储

函数

void setBit(char entry[], int nBits)
{
      entry[nBits/8] = entry[nBits/8] | (1 << (nBits%8) );
}

int checkBit(char entry[], int nBits)
{
      return (entry[nBits/8] & (1 << (nBits%8) ));
}

 

 

 

相关文章:

  • 2021-05-20
  • 2021-08-03
  • 2021-09-29
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2022-02-05
  • 2021-11-20
猜你喜欢
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2022-02-13
  • 2021-10-26
  • 2022-12-23
相关资源
相似解决方案