统计单字节、多字节bit位长度

时间:2023-01-11 17:54:28
#include<stdio.h>

//统计一个字节bit为1的个数
unsigned char CountBit(unsigned char value)
{
	unsigned char i=0;
	unsigned char count=0;
	while(i<8)
	{
		if(value & 0x01)
		{
			count++;
		}
		value>>=1;
		i++;
	}
	return count;
}

//统计多个字节bit为1的个数
unsigned long CountNBit(unsigned char *temp, unsigned long len)
{
	unsigned long count=0;
	unsigned long i=0;
	while(i<len)
	{
		count+=CountBit(temp[i]);
		i++;
	}
	return count;
}

int main()
{
	unsigned char temp[5]={0xfe,0xff,0x33,0xff,0xff};
	printf("temp数组的第一个元素的bit的长度: %d\n",CountBit(temp[0]));
	printf("temp数组的所有元素的bit的长度: %d\n",CountNBit(temp,sizeof(temp)));
}


运行 效果如下图所示:

统计单字节、多字节bit位长度