#include <stdio.h>
#include <stdint.h>
#define MASK_CONST 0xFU
unsigned char extractNibble(unsigned char reg, int pos)
{
uint8_t bit_pos = 4 * pos;
uint8_t mask = MASK_CONST << bit_pos;
reg = (reg & mask) >> bit_pos;
return reg;
}
int main() {
unsigned char reg;
int pos;
scanf("%hhu %d", ®, &pos);
printf("%d", extractNibble(reg, pos));
return 0;
}This code is a utility to extract a specific nibble (a 4-bit group) from an 8-bit register. Since a byte (8 bits) consists of exactly two nibbles, the code allows you to choose between the "low" nibble and the "high" nibble.
1. The Mask (#define MASK_CONST 0xFU)
The hexadecimal value 0xF is 1111 in binary. This constant acts as a template to "filter" 4 bits of data while ignoring everything else.
2. Calculating the Shift (bit_pos = 4 * pos)
Since each nibble is 4 bits wide:
pos = 0, the shift is 0 (accessing bits 0–3).pos = 1, the shift is 4 (accessing bits 4–7).3. Isolating the Bits (reg & mask)
By performing a bitwise AND, the program keeps only the bits where the mask is set to 1.
0xF0 (11110000).0.4. Aligning the Result (>> bit_pos)
After isolation, the bits are still in their original position (e.g., the high nibble is in the 4th–7th place). Shifting them back to the right aligns them to the 0th–3rd place so the function returns a value between 0 and 15.
Input
170 0
Expected Output
10