All submissions

Extract Bit Field from 16-bit Register

Approach & Code

#include <stdio.h>
#include <stdint.h>

/*
I/O
Input: 0x01F0 -> Binary = 0000 0001 1111 0000
5 bit value: 1111 
Output: 31

Input: 0x00B0
Output: 11

Plan:
- create a mask that will get the 5 bits from position 4 to 8
- then shift the masked value to the right by 4 
- then return this value to get the integer value required


16 bit number : 0000 0000 0000 0000
mask :          0000 0001 1111 0000   -> 0x01F0 (get the 4-8 bits)
then right shift the masked value by 4
0000 0000 0001 1111 -> 5 bit number to be returned 
*/

uint8_t extract_field(uint16_t reg) {
    // Your logic here
    uint8_t result = 0;
    uint16_t mask = 0x01F0;
    reg = reg & mask;
    result = reg >> 4U;

    return result;
}

int main() {
    uint16_t reg;
    scanf("%hx", &reg);
    printf("%u", extract_field(reg));
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

0x01F0

Expected Output

31