I'm trying to change the range of a gyroscope I'm using and there is the following guideline:

it is recommended to mask out (logical and with zero) reserved bits of registers which are partially marked as reserved.

I tried reading about bit masking with the bitwise operators and I feel I understand it for trying to read only certain bits, but not for writing.

For example, how would I write to the following register, masking out the 2 bits which are reserved? enter image description here


You always write a whole byte when you set the register. You only need to "mask out" those bits if there's a danger that you may inadvertently set them to 1, for instance through some value over flow from other bits when combining values together to form that byte.

If you're not doing that then there's nothing to mask out. For instance if you just want to set a specific set of bits then just set that value - 0b00101001 is going to be 0b00101001 whether you mask it or not.

If you decide you really want to mask a value, for instance if you are writing a library and you have no control over what an end user may decide to pass to a function, then & (or &=) is your friend:

uint8_t val = 0x55; // 0b01010101 in binary
val &= 0b00111111; // or 0x3F if you want to use HEX
// val is now 0x15 since bit 6 has been "masked" to 0.
  • Thank you for the detailed and informative answer. In your example, do you mean bit 7 and bit 8 are masked out? May 10 at 11:36
  • 1
    6 and 7. You start counting bits from 0.
    – Majenko
    May 10 at 11:38
  • Thank you again :) May 10 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.