是否有实际的限制位掩码的大小? [英] Is there a practical limit to the size of bit masks?

查看:182
本文介绍了是否有实际的限制位掩码的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有,以存储在一个变量的多个值,通过使用一个位掩码的常用方法。例如,如果用户读,写和说上一个项目的执行权限,也可以转换为一个单一的数字阅读= 4(2 ^ 2),写= 2(2 ^ 1) ,执行= 1(2 ^ 0),然后把它们相加得到7。

There's a common way to store multiple values in one variable, by using a bitmask. For example, if a user has read, write and execute privileges on an item, that can be converted to a single number by saying read = 4 (2^2), write = 2 (2^1), execute = 1 (2^0) and then add them together to get 7.

我用这种技术在多个Web应用程序,在那里我通常是变量存储到一个字段,并给它一个类型MEDIUMINT或什么的,这取决于不同值的数量。

I use this technique in several web applications, where I'd usually store the variable into a field and give it a type of MEDIUMINT or whatever, depending on the number of different values.

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

What I'm interested in, is whether or not there is a practical limit to the number of values you can store like this? For example, if the number was over 64, you couldn't use (64 bit) integers any more. If this was the case, what would you use? How would it affect your program logic (ie: could you still use bitwise comparisons)?

我知道,一旦你开始变得非常大套的价值观,不同的方法会是最佳的解决方案,但我感兴趣的这个方式的界限。

I know that once you start getting really large sets of values, a different method would be the optimal solution, but I'm interested in the boundaries of this method.

推荐答案

关闭我的头顶,我会写一个 SET_BIT GET_BIT ,可以采取的字节数组,有点数组中的偏移量,并使用一些位变换来设置/获取数组中的相应位功能。像这样的东西(在C,但希望你的想法):

Off the top of my head, I'd write a set_bit and get_bit function that could take an array of bytes and a bit offset in the array, and use some bit-twiddling to set/get the appropriate bit in the array. Something like this (in C, but hopefully you get the idea):

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

这篇关于是否有实际的限制位掩码的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆