lolololol ol
lolololol ol

Reputation: 868

Is there a difference between a bit mask and a bit array?

I have heard the two terms used interchangeably. Is there a difference?

For example,

unsigned char chessboard : 64; /* Bit mask */
unsigned char chessboard_2 [64]; /* Bit array */

Upvotes: 0

Views: 1698

Answers (2)

Barmar
Barmar

Reputation: 782498

Bit Mask

A bit mask is a binary value that's used to refer to specific bits in an integer value when using bitwise operators. For instance, you might have:

unsigned int low3 = 0x7;

This is a bit mask with the low order 3 bits set. You can then use it to extract a part of a value:

unsigned int value = 030071;
unsigned int value_low3 = value & low3; // result is 01

or to update part of value:

unsigned int newvalue = (value & ~low3) | 5; // result is 030075

Bit Array

A bit array is an unsigned integer, or an array of unsigned integers, that's used to hold a sequence of boolean flags, where each value is in separate bits of the integer(s). If you have lots of boolean values to store, this is saves lots of memory compared to having each of them in a separate array element.

However, there's a tradeoff: in order to access a specific flag, you need to use masking and shifting.

If your bit array is small enough to fit in a single integer, you might declare:

uint32_t bitarray;

Then to access a specific element of it, you use:

bitvalue = (bitarray >> bitnum) & 0x1;

and to set an element:

bitarray |= (1u << bitnum);

and to clear an element:

bitarray &= ~(1u << bitnum);

If the bit array needs multiple words, you declare an array. You get the array index by dividing the bit number by the number of bits in each array element, then use the remainder to determine the bit number within that word and use the above expressions.

Upvotes: 2

Swordfish
Swordfish

Reputation: 13144

None of them is a bitmask. The first is the definition of a bitfield which should only be valid as a struct member and the second is an array of 64 unsigned chars.

Upvotes: 3

Related Questions