Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

int main() {
    unsigned char reg;   // giá trị thanh ghi 8-bit (0-255)
    int pos;             // vị trí bit (0-7)
    int mode;            // 1: set, 0: clear

    // Nhập dữ liệu từ người dùng
    scanf("%hhu", &reg);  // %hhu cho unsigned char
    scanf("%d", &pos);
    scanf("%d", &mode);

    // Kiểm tra mode và thực hiện thao tác
    if (mode == 1) {
        reg |= (1 << pos);   // đặt bit ở vị trí pos
    } else if (mode == 0) {
        reg &= ~(1 << pos);  // xóa bit ở vị trí pos
    }

    // In kết quả sau khi thay đổi
    printf("%u\n", reg);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10