c語言的位操作

c語言的位操作

#include <stdio.h>

typedef unsigned char u8;

/* set the assigned bit to 1 */
#define SET_BIT(val, pos) \
        ((val) |= (1 << (pos)))

/* set the assigned bit to 0 */
#define CLEAR_BIT(val, pos) \
        ((val) &= ~(1 << (pos)))

/* set the assigned bit to opposite value */
#define FLIP_BIT(val, pos) \
        ((val) ^= (1 << (pos)))

/* set the assigned multiple bits to 1 */
#define SET_BITS(val, pos, offset) \
        ((val) |= ((1 << (offset)) - 1) << (pos))

/* set the assigned multiple bits to 0 */
#define CLEAR_BITS(val, pos, offset) \
        ((val) &= ~(((1 << (offset)) - 1) << (pos)))

/* set the assigned multiple bits to new value */
#define SET_NEW_BITS(val, pos, offset, new) \
        ((val) = CLEAR_BITS(val, pos, offset) | ((new) << (pos)))

/* print the byte with binary format */
void printf_bin(u8 val)
{
    int i = 8;

    while (i--){
        if ((val >> i) & 1){
            printf("1");
        }
        else{
            printf("0");
        }
    }
    printf("\n");
}


int main()
{
    u8 val = 0x55;  //0b01010101

    /* set bit */
    printf("set bit operation:\n");
    printf_bin(val);
    SET_BIT(val, 1);
    printf_bin(val);
    printf("\n");

    /* clear bit */
    printf("clear bit operation:\n");
    printf_bin(val);
    CLEAR_BIT(val, 1);
    printf_bin(val);
    printf("\n");

    /* flip bit */
    printf("flip bit operation:\n");
    printf_bin(val);
    FLIP_BIT(val, 1);
    printf_bin(val);
    printf("\n");
    FLIP_BIT(val, 1);

    /* set bits */
    printf("set bits operation:\n");
    printf_bin(val);
    SET_BITS(val, 0, 4);
    printf_bin(val);
    printf("\n");

    /* clear bits */
    printf("clear bits operation:\n");
    printf_bin(val);
    CLEAR_BITS(val, 0, 4);
    printf_bin(val);
    printf("\n");

    /* set new bits */
    printf("set new bits operation:\n");
    printf_bin(val);
    SET_NEW_BITS(val, 0, 4, 5);
    printf_bin(val);
    printf("\n");

    return 0;
}

輸出:

root@liu:~# gcc bitopt.c -o t
root@liu:~# ./t
set bit operation:
01010101
01010111

clear bit operation:
01010111
01010101

flip bit operation:
01010101
01010111

set bits operation:
01010101
01011111

clear bits operation:
01011111
01010000

set new bits operation:
01010000
01010101
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章