2018 April REVIEW
Arduino Bit Logic; Programming
2017 | by Gene Casanova
Senior Systems/Network/Internet/Robotics Engineer
When programming an embedded computer, like an Arduino system, the ability to manipulate individual bits is useful and sometimes necessary. Bit math becomes useful in programming the following processes:
- Save memory usage; by storing up to 8 'true' (1)/ 'false' (0) data values, in a single byte.
- Turning On/Off individual bits, in a control register or hardware port register.
- Performing certain arithmetic operations involving multiplying or dividing by powers of 2.
The Binary System
In the binary system, all integer values use only the values 0 and 1 for each digit. This is how virtually all computers store data internally. Each 0 or 1 digit is referred to as a "bit", short for "binary" digit.
The Arduino programming environment, enables specifing binary numbers by prefixing them with "0b". Example: 0b11 = = 3.
For legacy reasons, it also defines the constants "B0" through "B11111111", which can be used in the same way.
The bitwise 'AND' operator, in C++, is a single ampersand, '&', used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, then the resulting output is 1, otherwise the output is 0. Another way of expressing this is:
0 & 0 == 0
0 & 1 == 0
1 & 0 == 0
1 & 1 == 1
In Arduino, the type "int" is a 16-bit value; using '&' between two "int" expressions, causes 16 simultaneous 'AND' operations to occur. In a source code fragment like:
int a = 92; // in binary: 0000000001011100
int b = 101; // in binary: 0000000001100101
int c = a & b; // result: 0000000001000100, or 68 in decimal.
Each of the 16 bits in 'a' and 'b' are processed by using the bitwise 'AND', and all 16 resulting bits are stored in 'c', resulting in the value '01000100' in binary; 68 in decimal.
One of the most common uses of bitwise 'AND' is to select a particular bit (or bits) from an integer value, often referred to as "masking". For example, to access the least significant bit in a variable 'x', and store the bit in another variable 'y', use the following source code:
int x = 5; // binary: 101
int y = x & 1; // now y == 1
x = 4; // binary: 100
y = x & 1; // now y == 0
Use The Technology Wisely & Keep It Simple
Cyber Security Since 1979 - Consulting Available | IoT Full Stack And App Developer
CGI Computer Wares | EST 1979