Macro-Based Register Config Helper

Code

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

// Define macros here



#define SET_BIT(REG, BIT1) ((REG) |= (1U << (BIT1)))


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

    uint16_t result = 0x0000;

    if(enable == 1)
    {
        SET_BIT(result, 0);
    }
    else
    {
        result &= ~(1 << 0);
    }

    if(mode == 1)
    {
        SET_BIT(result, 1);
    }
    else if(mode == 2)
    {
        SET_BIT(result, 2);
    }
    else if(mode == 3)
    {
        SET_BIT(result, 1);
        SET_BIT(result, 2);
    }
    
    switch(speed)
    {
        case 1:
            result |= (1 << 3);
            break;
        case 2:
            result |= (1 << 4);
            break;
        case 3: 
            result |= (1 << 3);
            result |= (1 << 4);
            break;
        case 4:
            result |= (1 << 5);
            break;
        case 5: 
            result |= (1 << 5);
            result |= (1 << 3);
            break;
        case 6:
            result |= (1 << 4);
            result |= (1 << 5);
            break;
        case 7:
            result |= (1 << 3);
            result |= (1 << 4);
            result |= (1 << 5);
            break;

    }
    

    if(result & (1 << 6))
    {
        result &= ~(1 << 6);
    }

    if(result & (1 << 7))
    {
        result &=  ~(1 << 7);
    }

    return result;

    

    
}

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

 

 

 

Upvote
Downvote
Loading...

Input

1 2 4

Expected Output

37