Force a bit to 1/0

Icône de l'outil pédagogique Force to 1

 

In order to force a bit to 1, we make an OR operation.

We build a mask by putting to 1 the bits that we want to force to 1 and by keeping to 0 the ones that must remain unchanged.

For example, in order to force to 1 the bits 7 and 1 of variable a, the mask will be 0x082 and we will write :

a |= 0x82; ou a = a | 0x82;

 

After the operation, the value of a is 0xF7 in hexadecimal notation or 247 in decimal notation.

Icône de l'outil pédagogique Force to 0

 

In order to force a bit to 0, we operate a AND operation.

We build a mask by putting to 0 the bits that we want to force to 0 and by keeping to 1 the ones that must remain unchanged.

For example, in order to force to 1 the bits 5, 4 and 0 of variable a, the mask will be 0x0CE and we will write :

a &= 0xCE; ou a = a & 0xCE;

 

After the operation, the value of a is 0x44 in hexadecimal notation or 68 in decimal notation.