Macro-Based Register Config Helper

Code

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

// Define macros here
#define ENABLE(reg_bitval)   ((reg_bitval & 0x01) << 0 ) // As we are only setting one bit - 001 ; Setting Bit 0 (Shifting by 0 bits[As we are starting from bit 0])
#define MODE(reg_bitval)     ((reg_bitval & 0x03) << 1) // As we are setting two bits - 011 ; Setting Bits 1-2 (Shifting by 1 bit[As we are starting from bit 1]) //4 different MODE presets
#define SPEED(reg_bitval)    ((reg_bitval & 0x07) << 3) // 3 bits - The bit field is: 111 ; Setting Bits 3-5 (Shifting by 3 bits[As we are starting from bit 3]) // 8 differnt SPEED presets

/*
1. The AND operation is done between the reg_bitval and the no of bits allocated for each field 

Ex: As 3 bits are required to set SPEED - 000 to 111 - 8 possibilities 
Now assuming bit reg_val for SPEED as 3 - 011 - 0x03

So,  0x03 & 0x07 - 011 & 111 - 011 = 0x03

2. Shifting takes place
Now 0x03 gets shifted to the left by 3 bits -  0x03<<3 => 0000 0011 to 0001 1000*/

uint16_t build_register(uint8_t enable, uint8_t mode, uint8_t speed) {
    // Use macros to set fields
    uint16_t set_bit_fields_totalval = 0;

    set_bit_fields_totalval |=(ENABLE(enable));
    set_bit_fields_totalval |=(MODE(mode));
    set_bit_fields_totalval |=(SPEED(speed));

    return set_bit_fields_totalval;

}

int main() {
    uint8_t enable, mode, speed;
    scanf("%hhu %hhu %hhu", &enable, &mode, &speed);

    uint16_t reg = build_register(enable, mode, speed);
    printf("%u", reg);
    return 0;
}

Solving Approach

Setting bit fields from the appropriate positions by checking and extracting the values and then shifting accordingly

1. The AND operation is done between the reg_bitval and the no of bits allocated for each field 

Ex: As 3 bits are required to set SPEED - 000 to 111 - 8 possibilities 
Now assuming bit reg_val for SPEED as 3 - 011 - 0x03

So,  0x03 & 0x07 - 011 & 111 - 011 = 0x03

2. Shifting takes place
Now 0x03 gets shifted to the left by 3 bits -  0x03<<3 => 0000 0011 to 0001 1000

This is also what happens for the MODE Macro bit-field 


Finally, the result is ORed or added 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37