How to replace bits in a bitfield without affecting other bits using C

Use a bitmask. It is sort of like:

new_value = 0, 1, 2 or 3  // (this is the value you will set in)
bit_mask = (3<<5)         // (mask of the bits you want to set)
reg_data = (reg_data & (~bit_mask)) | (new_value<<5)

This preserves the old bits and OR’s in the new ones.

Leave a Comment