C语言对特定的bit位置1或置0

C语言常用的置位操作,涉及到的就是几个常用的位操作,原则就是:
对某位置0:原bit位与0
对某位置1:原bit位或1
相关代码:

#include 

int set_bit(int set_num, int position, int value) {
    switch (value)
    {
    case 0:
        set_num &= ~(1<<(position-1));
        break;
    case 1:
        set_num |= (1<<(position-1));
        break;
    
    default:
        break;
    }

    return set_num;
}

int main(int argc, char *argv[]){
    int set_num = 0;
    int position = 0;
    int bit_v = 0;
    int re = 0;

    printf("please enter the number of you want to set bit(0x): ");
    scanf("%d", &set_num);
    printf("please enter the position of you wang to set:");
    scanf("%d", &position);
    printf("please enter the value of you want to set:");
    scanf("%d", &bit_v);

    re = set_bit(set_num, position,bit_v);
    printf("the result is %d\n", re);

    return re;
}

以上代码中的position应当从1开始算(物理位置【狗头】)。如果position从0开始算的话,就不用对position减1了!

你可能感兴趣的:(C语言,c语言)