首页 > 解决方案 > 位掩码是否可以与位中的“访问数组”相媲美?

问题描述

对于我所看到的位掩码的所有定义,它们都只是深入研究如何位掩码、按位使用等,而没有解释其中任何一个的用例。更新您想要保留的所有位以及您想要清除的所有位以“访问数组”的目的是位吗?

标签: cbit-manipulationterminologymaskingbitmask

解决方案


更新您想要保留的所有位以及您想要清除的所有位以“访问数组”的目的是位吗?

我会说答案是否定的。

当您访问数组时,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_bitand的实现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

这只是使用“掩码”的几个示例,与将位作为数组访问无关。可以举出许多其他的例子。

所以得出结论:

掩码可用于编写以类似方式访问数组中的位的函数,但掩码也可用于许多其他事情。


推荐阅读