 # Using C bits

A prerequisite is needed to understand this article: know how to convert a decimal number to binary. It is also good to master the basic operations of Boolean algebra.

## Testing the value of the nth bit of a byte

To represent a byte in language C, we use the type 'unsigned char' because it is always 8 bits. Now all that is left to do is to write a small function to check the value of the nth bit of this byte. Take for example the number 0b10 which is two in base 10. One way to test if the second bit is 1 may be:
`if(byte==2)printf("Second bit is 1\n");`
Now consider a second example, 0b11 which is 3 in decimal. In this case, our test will fail (2! = 3) and will not enter the if. We could add this case as in the first example to obtain:
`if(byte==2 || byte==3)printf("Second bit is 1\n");`
The problem is that we have not yet processed all cases and there are 7 other bits in this byte. This is why we use a mask.

Mask works more or less like the game played by young children in which the goal is to enter the square which is in the square, the circle which is in the circle... (0bxxxxxx1x&0b10)=0b10 fhe form fits well (0bxxxxxx0x&0b10)=0b00 the form does not fit Applying the mask to the previous case:
`if(byte&2)printf("Second bit is 1\n");`
Be careful not to become confused, the two in the condition is the value of the second bit, the third bit value would be 4, its decimal value. It should be noted that two power n can be written as follows:
`printf("2 power %d=%d\n",n ,1<<n);`
This operation in fact amounts to taking the value 1 and to shift it of n bits to the left.

### Generic function

A generic function to test the nth bit of a byte could be:
```
char test_bit(unsigned char byte, char bit_position){
if(bit_position<0 || bit_position>7)return 0;
return byte & (1<<bit_position);
}
```

## Setting the nth bit of a byte to 1

To do that we use the 'or' and we have (0b01)or(0b10)=(0b11). Let's code it:
```
char set_bit(unsigned char *byte, char bit_position){
if(bit_position<0 || bit_position>7)return 0;
*byte=(*byte|(1<<bit_position));
return 1;
}
```

## Setting the nth bit of a byte to 0

To do that we use an inverted mask, the bit to set to zero is 0 and all the others 1. Then we apply an 'and' beetween our mask and the byte to change.
```
char unset_bit(unsigned char *byte, char bit_position){
if(bit_position<0 || bit_position>7)return 0;
*byte=(*byte& ~(1<<bit_position));
return 1;
}
```
Be The First To Comment.