Peter
Peter

Reputation: 57

What is the good solution for a bit masking issue?

The Problem

Question: what is the best masking solution. Especially for the unset masking.I

An example: changing bits[3:0] -> 0b1011 (data) purpose bits[3:0] -> 0b0110

Let me share what I tried:

And with this two masks I could use the bitwise operations.

int data = 0xB;         /*0b1011 (0xb) -> 0110 (0x6)*/
int umask = 0x9;        /*unset mask 0b1001*/
int smask = 0x6;       /*Set Mask 0b0110*/

data &= ~umask;        /*Unset the bits what needs without affecting other*/
data |= smask;         /*Set the bits what needs to be set*/

Upvotes: 3

Views: 265

Answers (1)

Michael Dorgan
Michael Dorgan

Reputation: 12515

The simple answer is yes, you use 1 mask to clear the bits you want to clear, and another to set the ones you want set. But, occasionally, there are hidden hardware level things you need to be aware of, depending on how the masks and data are used and what they represent.

If you just want to set your 4 bits to a value:

val &= ~(0xf); // This only clears the low 4 bits, preserving the rest.

assert((new4BitMaskvalue & ~0xf) == 0); // Make sure new mask only plays with low 4 bits.
val |= new4BitMaskvalue;  // or new mask

You are technically clearing some extra bits, but this allows you to use just one generic mask on clearing. You can also clear the exact bits as you do, but this may not be necessary.

Often you can just assign the whole value and save a step if you are setting all fields at once in a memory unit size supported by your CPU. (u8/u16/u32/u64/etc.)

Now, the "fun" part. If these bits represent actual hardware registers, you may not be able to set entire fields like this as it can cause exciting behavior. Perhaps this is an interrupt enable register. If so, clearing and resetting bits that don't need clearing and setting will cause unintended side effects. Also, registers are often read or write only, where again you need to be careful on how you mask and may even be forced to set or clear individual bits one at a time.

In short, yes, you usually need at least 2 values to clear and set bits. The first not and mask can generally be allowed to clear all bits you care about so that you don't need 2 special masks.

Upvotes: 2

Related Questions