c-bit相關操作

/**
 * @位操作符 
 * 1. |  或
 * 2. &  與
 * 3. ~  反
 * 4. ^  異或 (相同爲0,相異爲1. 與1異或等於反轉,與0異或等於保持)
 * 5. << 左移
 * 6. >> 右移
 */
/**
 * @位基本宏
 * note:  x  ->待操作的變量
 *        pos->待操作的第幾位    
 * 1.BITMASK(pos) 
 * 2.CLR_BIT(x,pos) 清除x的第pos位
 * 2.GET_BIT(x,pos) 讀取x的第pos位
 * 3.SET_BIT(x,pos) 設置x的第pos位 
 * 4.TOG_BIT(x,pos) 切換x的第pos位 
 */
#define BIT_MASK(pos)  (1U << (pos))
#define CLR_BIT(x,pos) ((x) & ~BIT_MASK(pos))
#define GET_BIT(x,pos) ((x) & BIT_MASK(pos)) ? 1 : 0)
#define SET_BIT(x,pos) ((x) | BIT_MASK(pos))
#define TOG_BIT(x,pos) ((x) ^ BIT_MASK(pos))
/**
 * @位域宏
 * note:  x,new->待操作的變量
 *        beg  ->待操作起始位 ranage [0-31]
 *        wth  ->待操作的位寬 ranage [1-32]
 * 1.BF_MASK(beg,wth)         第beg位開始,位寬wth相應位域的掩碼
 * 2.ENCODE_BF(new,beg,wth)   編碼new到第beg位開始,位寬wth的相應位域
 * 3.CLR_BF(x,beg,wth)        清除x的第beg位開始,位寬wth的相應位域
 * 4.GET_BF(new,beg,wth)      讀取x的第beg位開始,位寬wth的相應位域
 * 5.SET_BF(x,beg,wth,new)    設置x的第beg位開始,位寬wth的相應位域爲new
 * 6.TOG_BF(x,beg,wth)        切換x的第beg位開始,位寬wth的相應位域
 */
#define BF_MASK(beg,wth)       ((1U << (wth) - 1) << (beg))
#define ENCODE_BF(new,beg,wth) (((new) & BF_MASK(0,wth)) << (beg)) 
#define CLR_BF(x,beg,wth)      ((x) & ~BF_MASK(beg,wth))      
#define GET_BF(x,beg,wth)      (((x) >> (beg)) & BF_MASK(0,wth))
#define SET_BF(x,beg,wth,new)  (CLR_BF(x,beg,wth) | BF_ENCODE(new,beg,wth))
#define TOG_BF(x,beg,wth)      ((x) ^ BF_MASK(beg,wth)) 
//求某類型變量中bit爲1的個數
//http://graphics.stanford.edu/~seander/bithacks.html
int bit_count(unsigned char data)
{
	unsigned int count = 0;
	
	while (data != 0) {
		data &= (data-1);
		count++;
	}
	
	return count;
}
int bit_count(unsigned char data)
{
	unsigned char count = 0;
	
	while (data > 0) {
		if (data & 0x01)
			count++;
		data = data >> 1;
	}
	
	return 0;
}

int bit_count(unsigned char data)
{
	struct bit_bf {
		unsigned char b0:1;
		unsigned char b1:1;
		unsigned char b2:1;
		unsigned char b3:1;
		unsigned char b4:1;
		unsigned char b5:1;
		unsigned char b6:1;
		unsigned char b7:1;
	};
	struct bit_bf *bf = (struct bit_bf*)&data;
	
	return (bf->b0 + bf->b1 + bf->b2 + bf->b3 +    
	        bf->b4 + bf->b5 + bf->b6 + bf->b7);
}



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