宏BITS_TO_LONGS (数组位图操作) 代码测试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BITS_PER_LONG 32
#define BITS_PER_BYTE       8  
#define BITS_TO_LONGS(nr)       DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))//nr个位需要多少个long型数据变量来存储
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d)) 
转载请注明原文地址:http://blog.csdn.net/oyhb_1992/article/details/77680363
static inline void set_bit(int nr, unsigned long *addr)  
{  
	addr[nr / BITS_PER_LONG] |= 1UL << (nr % BITS_PER_LONG);  
}  

static inline void clear_bit(int nr, unsigned long *addr)  
{  
	addr[nr / BITS_PER_LONG] &= ~(1UL << (nr % BITS_PER_LONG)); 
}  

static __always_inline int test_bit(unsigned int nr, const unsigned long *addr)  
{  
	return ((1UL << (nr % BITS_PER_LONG))&(((unsigned long *)addr)[nr / BITS_PER_LONG])) != 0;    
}  

// 十进制转换为二进制,十进制数的每1bit转换为二进制的1位数字
char *int_to_bin(unsigned long data)
{
	unsigned int i = 0;
	int bit_num = sizeof(unsigned long) * 8;
	char *p_bin = (char *)malloc(sizeof(char)*(bit_num+1));
	//char *p_bin = new char[bit_num+1];
	p_bin[bit_num] = '\0';
	for (i = 0; i < bit_num; ++i)
	{
		//p_bin[i] = data << i >> (bit_num-1);//获取第i位
		//p_bin[i] = data>> (bit_num-1);
		p_bin[i] = data&(1<<i);//等价于上面两条语句
		if (p_bin[i] == 0)
			p_bin[i] = '0';
		else if (p_bin[i] != 0)
			p_bin[i] = '1';
	}
	return p_bin;
}

// 十进制转换为十六进制,十进制数的每4bit转换为十六进制的1位数字
char *int_to_hex(unsigned long data)
{
	unsigned int i = 0;
	int bit_num = sizeof(unsigned long) * 8;
	char *p_hex = (char *)malloc(sizeof(unsigned long)*8/4+3);
	p_hex[0] = '0';
	p_hex[1] = 'x';
	p_hex[bit_num/4+2] = '\0';
	char *p_tmp = p_hex + 2;
	for (i = 0; i < bit_num/4; ++i)
	{
		p_tmp[i] = data << (4*i) >> (bit_num-4);
		if (p_tmp[i] >= 0 && p_tmp[i] <= 9)
			p_tmp[i] += '0';
		else if (p_tmp[i] >= 10 && p_tmp[i] <= 15)
			p_tmp[i] = p_tmp[i] - 10 + 'A';
	}
	return p_hex;
}

int main()
{
	#define EV_MAX			0x1f
	#define EV_CNT			(EV_MAX+1)   //32
	int i=0,j=0;
	unsigned long evbit[BITS_TO_LONGS(EV_CNT)];   //32个位共需要多少个long型数据来存储

	memset(evbit,0,sizeof(evbit));
	//等价于
	/*for(i=0;i<sizeof(evbit)/sizeof(long);i++)
		for(j=0;j<BITS_PER_LONG/BITS_PER_BYTE;j++)
		{
			char *p = (char *)(&evbit[i]);
			p[j] = 0;  
		}*/

	for(i=0;i<sizeof(evbit)/sizeof(unsigned long);i++)
	{
		char *p = int_to_bin(evbit[i]);
		printf("p[%d] = %s\n",i,p++);   
	}

	//第7位设为1
	set_bit(7,evbit);
	//测试第7位是否为1
	int test = test_bit(7,evbit);	
	printf("test_bit nr = 7 value = %d\n",test);
	for(i=0;i<sizeof(evbit)/sizeof(unsigned long);i++)
	{
		char *p = int_to_bin(evbit[i]);
		printf("p[%d] = %s\n",i,p++);   
	}
	return 0;
}



测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值