When assigning values to registers using the C language, bit manipulation techniques in C are often required.C language bit manipulation methods.
Clearing a specific bit in a register
Assuming ‘a’ represents the register, which already has a value. If we want to clear a specific bit while keeping other bits unchanged, the code is as follows.
// Define a variable a = 1001 1111 b (binary number)unsigned char a = 0x9f;// Clear bit2a &= ~(1<<2);// The 1 in parentheses is left-shifted by two bits, (1<<2) results in the binary number: 0000 0100 b// Bitwise NOT, ~(1<<2) results in 1111 1011 b// Assuming the original value of a in binary is: a = 1001 1111 b// The resulting number is ANDed with a, a = (1001 1111 b)&(1111 1011 b),// After the operation, the value of a is a=1001 1011 b// The bit2 of a is cleared, while other bits remain unchanged.
Clearing several consecutive bits in a register
Since there are sometimes several consecutive bits in a register used to control a certain function, let’s assume we need to clear several consecutive bits in the register while keeping other bits unchanged, the code is as follows.
// If we divide the binary bits of a into groups of 2// i.e., bit0, bit1 is group 0, bit2, bit3 is group 1,// bit4, bit5 is group 2, bit6, bit7 is group 3// To clear bit2 and bit3 of group 1a &= ~(3<<2*1);// The 3 in parentheses is left-shifted by two bits, (3<<2*1) results in the binary number: 0000 1100 b// Bitwise NOT, ~(3<<2*1) results in 1111 0011 b// Assuming the original value of a in binary is: a = 1001 1111 b// The resulting number is ANDed with a, a = (1001 1111 b)&(1111 0011 b),// After the operation, the value of a is a=1001 0011 b// The bit2 and bit3 of group 1 are cleared, while other bits remain unchanged.// The (1) in (~(3<<2*1)) is the group number; to clear bit6 and bit7 of group 3, this should be 3// The (2) in parentheses is the number of bits per group; if divided into groups of 4, this should be 4// The (3) in parentheses is the value when all bits in the group are 1; if divided into groups of 4, this should be the binary number "1111 b"// For example, to clear bit4 and bit5 of group 2a &= ~(3<<2*2);
Assigning values to specific bits in a register
After clearing the bits in the register, it becomes convenient to write the required values to specific bits, the specific code is as follows.
// a = 1000 0011 b// Now set the cleared bit4 and bit5 of group 2 to the binary number "01 b" a |= (1<<2*2);// a = 1001 0011 b, successfully set the value of group 2, other groups remain unchanged
Inverting a specific bit in a register
To invert a specific bit in a register, i.e., change 1 to 0 and 0 to 1, this can be done directly using the following operation.
// a = 1001 0011 b// Invert bit6, other bits remain unchanged a ^=(1<<6);// a = 1101 0011 b