1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <math.h>

unsigned int modifyBit(unsigned int reg, int pos, int mode) {
    int a[8];
    for(int i=0; i<8; i++){
        a[i] = (reg%2);
        reg/=2;
    }
    a[pos] = mode;
    int ans = 0;
    for(int i=0; i<8; i++){
        ans+=a[i]*pow(2,i);
    }
    return ans;
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote