#include "main.h"
/**
* get_bit - returns the value of a bit at a given index
* @n: the number
* @index: the index of the bit we want to print
* Return: value of the bit
*/
int get_bit(unsigned long int n, unsigned int index)
{
int bit_value;
if (index > 63)
return (-1);
bit_value = (n >> index) & 1;
return (bit_value);
}
- 81,885
- 6
- 58
- 85
- 7
- 3
2 Answers
On your system unsigned long is a 64-bit value. The bit numbers (indexes) range from 0 - 63. If you are looking for an index greater-than 63 that is an error and -1 is returned. Otherwise, you shift the bits to the right (bits 0 - index - 1 fall off the right side (are shifted off)) leaving bits 63 - index. ANDing with 1 simply results in 1 or 0 depending on whether the bit at index is 1 or 0.
An Example
Let's take an example of the number 12 where bits at index 2 (the 4's bit) and 3 (the 8's bit) are both one (bits at indexes 4 - 63 are all 0, represented by .. below). You want to determine whether the bit at index 2 is 1 or 0 (on or off).
The binary representation of the number 12 is:
..1100
The index is 2. So shifting the value to the right by 2 (e.g. n >> index) results in the number 3, e.g.:
..0011
When you AND a number with 1 you are ANDing all bits with ..00000001 (showing only the final byte, all other bits are 0). The process of ANDing 3 and 1 is, and will result in:
..0011 AND
..0001
------
..0001
So in the number 12 the bit at index == 2 is 1. (if you try again with index == 1 or index == 4 the result is 0)
- 81,885
- 6
- 58
- 85
It returns -1 for all positions greater than 64, that's the first if() check.
Then it right shifts the number by given index, and checks whether the bit is set or not.
shifted_number = bit >> index;
check = shifted_number & 1;
- 5,438
- 2
- 27
- 32
-
You are incorrect, no assignment to `n` is happening there. – Tanveer Badar Apr 29 '22 at 05:44
-
You are incorrect. There are no modifications happening in `shifted_number & 1`. – Tanveer Badar Apr 29 '22 at 08:45
-
You are again incorrect. `&` operator doesn't modify. There are no modifications happened in `shifted_number & 1`. – Tanveer Badar Apr 29 '22 at 17:57