Set or Clear a Specific Bit in a Register

Code

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

int main() {
    uint8_t reg;
    int bit_pos;
    int mode;

    // Nhập dữ liệu
    scanf("%hhu", &reg);      // giá trị thanh ghi 0–255
    scanf("%d", &bit_pos);    // vị trí bit 0–7
    scanf("%d", &mode);       // 1 = set, 0 = clear

    // Kiểm tra đầu vào hợp lệ (không bắt buộc nhưng tốt)
    if (bit_pos < 0 || bit_pos > 7 || (mode != 0 && mode != 1)) {
        printf("Invalid input\n");
        return 0;
    }

    // Thực hiện thao tác
    if (mode == 1) {
        // Set bit
        reg |= (1 << bit_pos);
    } else {
        // Clear bit
        reg &= ~(1 << bit_pos);
    }

    // In kết quả
    printf("%u", reg);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10