位掩码的大小有实际限制吗?

nic*_*ckf 5 sql bit-manipulation bitmask

有一种通用的方法,可以使用位掩码将多个值存储在一个变量中。例如,如果用户对某项具有读,写和执行特权,则可以通过说出read = 4 (2^2), write = 2 (2^1), execute = 1 (2^0)将其转换为单个数字,然后将它们加在一起得到7。

我在几种Web应用程序中使用了此技术,通常将变量存储到一个字段中,并根据不同值的数量为它提供MEDIUMINT或其他类型。

我感兴趣的是,这样存储的值数量是否有实际限制?例如,如果数字超过64,则不能再使用(64位)整数。如果是这样,您将使用什么?它会如何影响您的程序逻辑(即:您是否仍可以使用按位比较)?

我知道一旦您开始获得非常多的值集,一种不同的方法将是最佳解决方案,但是我对这种方法的边界很感兴趣。

Mik*_*oss 3

我突然想到,我会写一个set_bitandget_bit函数,它可以接受一个字节数组和数组中的一个位偏移量,并使用一些位调整来设置/获取数组中的适当位。像这样的东西(用C语言,但希望你能明白):

// sets the n-th bit in |bytes|. num_bytes is the number of bytes in the array
// result is 0 on success, non-zero on failure (offset out-of-bounds)
int set_bit(char* bytes, unsigned long num_bytes, unsigned long offset)
{
  // make sure offset is valid
  if(offset < 0 || offset > (num_bytes<<3)-1) { return -1; }

  //set the right bit
  bytes[offset >> 3] |= (1 << (offset & 0x7));

  return 0; //success 
}

//gets the n-th bit in |bytes|. num_bytes is the number of bytes in the array
// returns (-1) on error, 0 if bit is "off", positive number if "on"
int get_bit(char* bytes, unsigned long num_bytes, unsigned long offset)
{
  // make sure offset is valid
  if(offset < 0 || offset > (num_bytes<<3)-1) { return -1; }

  //get the right bit
  return (bytes[offset >> 3] & (1 << (offset & 0x7));
}
Run Code Online (Sandbox Code Playgroud)