Q:

How to set, clear, toggle and checking a single bit in C?

0

How to set, clear, toggle and checking a single bit in C?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Note: Here I assume that bit of register starts with 0th position, it means the 2nd position is actually 3rd bits.

D7 D6 D5 D4 D3 D2 D1 D0

 

Setting N-th Bit

Setting an N-th bit means that if the N-th bit is 0, then set it to 1 and if it is 1 then leave it unchanged. In C, bitwise OR operator (|) use to set a bit of integral data type. As we know that | (Bitwise OR operator) evaluates a new integral value in which each bit position is 1 only when operand’s (integer type) has a 1 in that position.

In simple words, you can say that “Bitwise OR ” of two bits is always one if any one of them is one.

That means,
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
Algorithm to set the bits:
Number | = (1UL << nth Position);
Clearing a Bit

Clearing a bit means that if N-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged. Bitwise AND operator (&) use to clear a bit of integral data type. “AND” of two bits is always zero if any one of them is zero.

That means,
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
Algorithm to clear the bit:

To clear the nth bit, first, you need to invert the string of bits then AND it with the number.

Number &= ~(1UL << nth Position);
Checking a Bit

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.

An algorithm to check the bit
Bit = Number & (1UL << nth);
Toggling a Bit

Toggling a bit means that if the N-th bit is 1, then change it to 0 and if it is 0 then change it to 1. Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

That means,
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0
An algorithm to toggle the bits
Number ^= (1UL << nth Position);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Embedded C interview questions and answers (2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What will be the output of the below C program?... >>
<< What is the difference between const and macro?...