#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;
}
测试结果: