5
9
2014
0

bitmap操作

一下代码实现了位图的基本操作

/*以addr指向位置为起始地址,第nr个bit位的操作
  内容来自于文件系统中内核源码。bitmap.h
*/


//返回1,则该bit位为1
static  int happyhut_test_bit(unsigned int nr,char * addr) 
{
   //addr为char * 类型,一个char* 为8个bit,故addr[nr>>3],使其指向该nr对应的字节
   //(1<<(nr&7))确定该字节要test的bit位
  return (addr[nr >> 3] & (1<<((nr & 7)))) != 0;
}

static  int happyhut_set_bit(unsigned int nr,char * addr)
{
  int __res = happyhut_test_bit(nr,addr);
  addr[nr >> 3] |= (1<<((nr & 7)));//按位或,置1
  return __res != 0; \
}
//置0
static  int happyhut_clear_bit(unsigned int nr,char * addr)
{
  int __res = happyhut_test_bit(nr,addr);
  addr[nr >> 3] &= ~(1<<((nr & 7)));
  return __res != 0;
}
static int happyhut_test_and_clear_bit(unsigned int nr,char * addr)
{
	int __res = happyhut_test_bit(nr,addr);
	if(__res)//返回值为1,则该bit位为1
	happyhut_clear_bit(nr,addr);
	return __res;
}
static  int happyhut_test_and_set_bit(unsigned int nr,char * addr)
{
       int __res=happyhut_test_bit(nr,addr);
	 if(!__res)
	 happyhut_set_bit(nr,addr);
	 return __res;
	 	
}
//找第一个0的bit位
static int happyhut_find_first_zero_bit(char *addr,unsigned int size)
{
 unsigned int index;
 for(index=0;index<size;index++)
	 if(!happyhut_test_bit(index,addr))
		 return index;
 return index;
}

下面看图,帮助理解。addr指向一个char,char占8个字节

 

Category: 编程理解 | Tags: | Read Count: 875

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com