- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clear/Set a specific bit of a number in Arduino
When you delve into advanced firmware, you deal with a lot of registers, whose specific bits need to be set or cleared depending on your use case. Arduino has inbuild functions to do that.
Syntax
bitSet(x, index)
and,
bitClear(x, index)
Where x is the number whose bit has to be set/ cleared and index is the position of the bit (0 for least significant or right-most bit). This function makes changes in the number x in place, and also returns the updated value of x.
Note that setting a bit means setting its value to 1, and clearing it means setting its value to 0.
Example
The following example illustrates the use of these functions −
void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); int x = 6; Serial.println(x); bitSet(x,0); Serial.println(x); bitClear(x,2); Serial.println(x); bitClear(x,3); Serial.println(x); } void loop() { // put your main code here, to run repeatedly: }
Output
The Serial Monitor output is shown below −
As you can see, we start off with the number 6 (0b0110).
We then set its 0th bit, yielding (0b0111), which corresponds to 7.
Then, we clear its 2nd bit, yielding (0b0011), which corresponds to 3.
We then clear its 3rd bit, which was already 0. Thus, we again get (0b0011), which corresponds to 3.
The Serial Monitor output shows these numbers in the exact sequence we just described.
- Related Articles
- Read a specific bit of a number with Arduino
- Python Program to Clear the Rightmost Set Bit of a Number
- Map a 10-bit number to 8-bit in Arduino
- How do you set, clear, and toggle a bit in C/C++?
- Find if a string begins with a specific set of characters in Arduino
- Clear a bit in a BigInteger in Java
- Set characters at a specific position within the string in Arduino
- Find most significant set bit of a number in C++
- Position of the K-th set bit in a number in C++
- For every set bit of a number toggle bits of other in C++
- Set the bit at a specific position in the BitArray to the specified value in C#?
- Queries for number of array elements in a range with Kth Bit Set using C++
- Set a bit for BigInteger in Java
- How to find a nearest higher number from a specific set of numbers: JavaScript ?
- How to clear the EEPROM with Arduino?
