1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // check if the given reg val is within bounds 
    if (reg < 0 || reg > 255) {
        printf("Reg value out of bounds\n");
        return -1;
    }

    // check if the given pos val is within bounds 
     if (pos < 0 || pos > 7) {
        printf("Reg value out of bounds\n");
        return -1;
    }

    // check if the given mode val is within bounds 
     if (mode < 0 || mode > 1) {
        printf("Reg value out of bounds\n");
        return -1;
    }

    // if the mode is 0, clear the bit 
    if (mode == 0) {
        return reg &= ~(1 << pos); 
    }

    else if (mode == 1) {
        return reg |= (1 << pos);
    }

    return -1; 

    // otherwise, if the mode is 1, set the bit 
    return 0;
}

int main() {
    unsigned char reg;
    int pos, mode;
    scanf("%hhu %d %d", &reg, &pos, &mode);
    printf("%d", modifyBit(reg, pos, mode));
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote