對數值位操作,使用“移位”操作,提高速度;
通過“宏”的形式來封裝,避免函數調用,提供速度;
//========================================================================
#include <stdio.h>
//======================================
//獲取 val 數值的第 b 位(從0位開始算);
//======================================
int num_get_bit(int val, int b)
{
int t, v;
int x;
t = 1 << b;
v = val & t;
x = v >> b;
return x;
}
//======================================
//獲取 val 數值的第 b 位(從0位開始算);
//======================================
#define BIT_GET_VAL(val, b) \
((val & (1 << b)) >> b)
//======================================
//設置 val 數值的第 b 位爲1值;
//======================================
#define BIT_SET(val, b) \
val = val | (1 << b)
//======================================
//清除 val 數值的第 b 位, 就是設置爲0值;
//======================================
#define BIT_CLEAR(val, b) \
val = val & ~(1 << b)
//======================================
//======================================
int main(void)
{
//int x = 0x07;
//int x = 0x8f;
int x = 0;
BIT_SET(x, 0);
BIT_SET(x, 1);
//BIT_SET(x, 2);
BIT_SET(x, 3);
// BIT_SET(x, 4);
BIT_SET(x, 5);
BIT_SET(x, 6);
// BIT_SET(x, 7);
printf("x0 = %d\n", num_get_bit(x, 0));
printf("x1 = %d\n", num_get_bit(x, 1));
printf("x2 = %d\n", num_get_bit(x, 2));
printf("x3 = %d\n", num_get_bit(x, 3));
printf("x4 = %d\n", num_get_bit(x, 4));
printf("x5 = %d\n", num_get_bit(x, 5));
printf("x6 = %d\n", num_get_bit(x, 6));
printf("x7 = %d\n", num_get_bit(x, 7));
printf("======================\n");
printf("x0 = %d\n", BIT_GET_VAL(x, 0));
printf("x1 = %d\n", BIT_GET_VAL(x, 1));
printf("x2 = %d\n", BIT_GET_VAL(x, 2));
printf("x3 = %d\n", BIT_GET_VAL(x, 3));
printf("x4 = %d\n", BIT_GET_VAL(x, 4));
printf("x5 = %d\n", BIT_GET_VAL(x, 5));
printf("x6 = %d\n", BIT_GET_VAL(x, 6));
printf("x7 = %d\n", BIT_GET_VAL(x, 7));
printf("hehe ...\n");
return 0;
}