题目:请编写一个c函数,该函数给出一个字节中被置为1的位的个数
#include <stdio.h>
int func1(char n)
{
int count = 0;
int i;
for (i = 0; i < 8; i++)
{
if (n&1 == 1)
count++;
n = n >> 1;
}
return count;
}
int main(){char n = 9;int res = func1(n);printf ("%d\n",res);return 0;}union A{int b;char ch;};方法一:
方法二: int main() { union A a; a.b = 9; int res = func2(a.ch); printf ("%d\n",res); return 0; } 方法三: int main() { int n = 9; int ch; int *p = &n; char *pch = (char *)p; int res = func3(*pch); printf ("%d\n",res); return 0; }