VOOZH about

URL: https://www.geeksforgeeks.org/c/extract-bits-in-c/

⇱ Extract bits in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extract bits in C

Last Updated : 31 Jul, 2024

In C programming, extracting a bit means retrieving the value (0 or 1) of a bit or a group of bits present at a specific position in the binary representation of a number

In this article, we will learn how to extract a bit or multiple bits at given positions in a binary number. We will also explore how to extract a range of bits simultaneously.

How to Extract a Bit in C?

In C, we can extract a given bit using the AND operator (&) combined with a bit mask and then right shifting the result. Let's see how it is possible with the help of the truth table of AND:

👁 Truth-Table-for-AND-Operation

From the above table, we can infer that:

  • By ANDing a bit with 1, we can extract the bit's value.
  • By ANDing a bit with 0, the result is always 0.

Extracting a Single Bit from Specific Position

To extract a specific bit in a number, you can use a bit mask with the AND operator and then right shift the result to get the bit's value.

Approach

  1. Create a mask with only kth bit set to 1.
  2. Apply the mask using &.
  3. Right-Shift the resultant number k times, where k is the position of the bit you wanted to extract.

Example:

Input:
binary_number: 01100111
bit to extract: 5th

Output:
extracted_bit: 0

Program to Illustrate How to Extract a Specific Bit in C


Output
Extracted Bit: 0

Time Complexity: O(1)
Space Complexity: O(1)

Extracting Multiple Bits in C

We can also extract multiple bits by creating a mask with the desired bits set to 1 and then right shifting the result to get the bits' values.

Approach

  1. Create a mask with n bits set to 1 in the range k and l, where k and l is the range you want to extract bits from.
  2. Apply the mask using &.
  3. Right-Shift the resultant number k number of times, where k is the starting position of the bits you want to extract.

Example:

Input:
binary_number: 01100111
bit to extract: 5th to 7th

Output:
extracted_bits: 110

Program to Illustrate How to Extract Multiple Bits in C


Output
Extracted Bits: 6

Time Complexity: O(1), Bitwise operations and shifts are constant-time operations.
Auxiliary Space: O(1)

Conclusion

By following these methods, you can efficiently extract specific bits, multiple bits, or a range of bits from a binary number in C, allowing for precise control and manipulation of binary data.

Comment
Article Tags: