In a microcontroller, where the computational resources (CPU power, memory, speed) are very precious , often information is managed at single bit level.
Bit means "binary digit". The number of bit is the number of binary digit of the internal number representation. A number can be rebresented by using a "base" notation.
We are used to represent number in the decimal base, by using ten digit (from zero to nine). It means that each digit of a number, going from rigth to left, has a weight obtained by calculating $10^i$ where i is the numebr representing the position of the digit in the number, starting from zero in the rigthmost position. So the decimal number 435 means:
$4(10^2)+3(10^1)+5(10^0)$
If you want to represent number by using binary number, we will allowed to use only two different digit (zero and one). So the binary number 10011 means:
$1(2^4)+0(2^3)+0(2^2)+1(2^1)+1(2^0)$
By solving this easy calcolus, the result is (in decimal reprensentation): 19
Each binary digit can be easily implemented with a very simple electronic circuit that will represent only two status: high voltage, low voltage or closed circuit, open circuit.
So each binary digit can represent the status of a flag, of a variable, of a entity. If you want set or read a single bit in a binary number you can use the "masking" technique.
To understand the masking technique, before we have to better understand the behavior of some logical operators or functions.
Or
given two binary variables that can assume only values 1 or 0, the "or" combination of this two variables can be written as:
a | b
It means that the result is 1 if a or b are 1. Also if both variables are 1 the result is one.
And
the "and" combination of the two variables a and b can be written as:
a & b
It means that the result is 1 if a and b are 1.
Masking means to use a binary number to read or set single bit in a binary number.
For instance we have a variable valorised to decimal 7 and we use a four bit representation, the equivalent binary number is: 0111.
Read
If you want to read only the third bit you can use a binary mask with only a 1 in the same position of the bit that we want to read: 0100.
If you do the binary and bit by bit between the two number you have:
0111 &
0100 =
0100
If the result is greater than 0 the interested bit is set to 1, otherwise it is 0.
Set
If you want to set only the fourth bit you can use a binary mask with only a 1 in the same position of the bit that we want to set: 1000.
If you do the binary or bit by bit between the two number you have:
0111 |
1000 =
1111
Said this, in some Thymio programs you can find esoteric coding like:
if (state & 1) ==1 then
...
It means that the if condition will be verified if the first bit of the state variable is set to 1.
Values of state like 1, 3, 5 (more in general odd values), will satisfy the condition.
Sic Parvis Magna