Skip to content

Commit 018e653

Browse files
authored
Merge pull request #933 from arduino/karlsoderby/bit-rw
bitRead & bitWrite Improvements
2 parents c3d6ad9 + b9ee540 commit 018e653

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

Language/Functions/Bits and Bytes/bitRead.adoc

+49-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ subCategories: [ "Bits and Bytes" ]
1717

1818
[float]
1919
=== Description
20-
Reads a bit of a number.
20+
Reads a bit of a variable, e.g. `bool`, `int`. Note that `float` & `double` are not supported. You can read the bit of variables up to an `unsigned long long` (64 bits / 8 bytes).
2121
[%hardbreaks]
2222

2323

@@ -36,6 +36,54 @@ Reads a bit of a number.
3636
=== Returns
3737
The value of the bit (0 or 1).
3838

39+
=== Example Code
40+
41+
This example code demonstrates how to read two variables, one increasing counter, one decreasing counter, and print out both the binary and decimal values of the variables.
42+
43+
The `readBit()` function loops through each bit of the variable (starting from the rightmost bit), and prints it out.
44+
45+
[source,arduino]
46+
----
47+
long negative_var = -0; //
48+
unsigned long long positive_var = 0;
49+
50+
//predefined sizes when looping through bits
51+
//e.g. long_size is 32 bit (which is 0-31). Therefore, we subtract "1".
52+
const int bool_size = (1 - 1);
53+
const int int_size = (8 - 1);
54+
const int long_size = (32 - 1);
55+
56+
void setup() {
57+
Serial.begin(9600);
58+
}
59+
60+
void loop() {
61+
//run readBit function, passing the pos/neg variables
62+
readBit("Positive ", positive_var);
63+
readBit("Negative ", negative_var);
64+
Serial.println();
65+
66+
//increase and decrease the variables
67+
negative_var--;
68+
positive_var++;
69+
70+
delay(1000);
71+
}
72+
73+
/*this function takes a variable, prints it out bit by bit (starting from the right)
74+
then prints the decimal number for comparison.*/
75+
void readBit(String direction, long counter) {
76+
Serial.print(direction + "Binary Number: ");
77+
//loop through each bit
78+
for (int b = long_size; b >= 0; b--) {
79+
byte bit = bitRead(counter, b);
80+
Serial.print(bit);
81+
}
82+
Serial.print(" Decimal Number: ");
83+
Serial.println(counter);
84+
}
85+
----
86+
3987
--
4088
// OVERVIEW SECTION ENDS
4189

Language/Functions/Bits and Bytes/bitWrite.adoc

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ subCategories: [ "Bits and Bytes" ]
1717

1818
[float]
1919
=== Description
20-
Writes a bit of a numeric variable.
20+
Writes to a bit of a variable, e.g. `bool`, `int`, `long`. Note that `float` & `double` are not supported. You can write to a bit of variables up to an `unsigned long` (32 bits / 8 bytes).
2121
[%hardbreaks]
2222

2323

0 commit comments

Comments
 (0)