c - 位掩码是否可以与位中的“访问数组”相媲美?
问题描述
对于我所看到的位掩码的所有定义,它们都只是深入研究如何位掩码、按位使用等,而没有解释其中任何一个的用例。更新您想要保留的所有位以及您想要清除的所有位以“访问数组”的目的是位吗?
解决方案
更新您想要保留的所有位以及您想要清除的所有位以“访问数组”的目的是位吗?
我会说答案是否定的。
当您访问数组时,int
您将执行以下操作:
int_array[index] = 42; // Write access
int x = int_array[42]; // Read access
如果您想编写类似的函数来读取/写入特定位,例如以unsigned int
“类似数组的方式”,它可能如下所示:
unsigned a = 0;
set_bit(a, 4); // Set bit number 4
unsigned x = get_bit(a, 4); // Get bit number 4
set_bit
and的实现get_bit
将需要(除其他外)一些按位掩码操作。
所以是的 - 要以“像数组一样的方式”访问位,您需要屏蔽但是......
位级掩码还有许多其他用途。
例子:
int buffer[64];
unsigned index = 0;
void add_to_cyclic_buffer(int n)
{
buffer[index] = n;
++index;
index &= 0x3f; // Masking by 0x3f ensures index is always in the range 0..63
}
例子:
unsigned a = some_func();
a |= 1; // Make sure a is odd
a &= ~1; // Make sure a is even
例子:
unsigned a = some_func();
a &= ~0xf; // Make sure a is a multiple of 16
这只是使用“掩码”的几个示例,与将位作为数组访问无关。可以举出许多其他的例子。
所以得出结论:
掩码可用于编写以类似方式访问数组中的位的函数,但掩码也可用于许多其他事情。
推荐阅读
- reporting-services - 当我什么都不作为参数传递时,我的表达式出现错误
- php - PHP 即使密码是好的形式播种它也是有效的
- openshift - 我们可以使用 env 变量作为 openshift 部署容器中 ENV 变量的值吗?
- swift - 拖放类似于 Finder 应用程序 NSOutlineView Cocoa Swift
- sql - 如何在周末获得所有批准的记录?
- r - 从 github 获取多个 r 脚本
- sql - 选择两个数组的元素与模式不匹配的行
- python - 模块“tensorflow.python.platform.flags”没有属性“trace”
- javascript - onClick 通过使用键迭代数据并替换为状态中的新数据来替换以前的状态项?
- apache-spark - 验证一个 pyspark Dataframe 中的行数据与另一个 Dataframe 匹配