1.返回一个整数二进制中1的个数
int count_one_bits(unsigned int value)
{
int i = 0 ;
int count = 0 ;
for (i = 0 ; i < 32 ; i++)
{
if (((value >> i)&1 ) == 1 )
{
count++;
}
}
return count;
}
int main()
{
int n = -1 ;
int m = 0 ;
printf ("请输入一个数:" );
//scanf ("%d " , &n);
m = count_one_bits(n);
printf ("二进制中1的个数为%d \n" , m );
system ("pause" );
return 0 ;
}
2.分别输出一个数的二进制序列中所有的奇数为和偶数位
#include<stdio.h>
#include<stdlib.h>
int main()
{
int m = 0 ;
int i = 0 ;
printf ("请输入一个数:" );
scanf ("%d" , &m);
printf ("奇数位为:" );
for (i = 30 ; i >= 0 ; i-=2 )
{
if (((m>>i)&1 ) ==1 )
printf (" 1" );
else
{
printf (" 0" );
}
}
printf ("\n偶数位为:" );
for (i = 31 ; i >= 1 ; i-=2 )
{
if (((m>>i)&1 ) ==1 )
printf (" 1" );
else
{
printf (" 0" );
}
}
system("pause" );
return 0 ;
}
3.输出一个整数的每一位
#include<stdio.h>
#include<stdlib.h>
int main()
{
int m = 0 ;
int a = 0 ;
printf ("请输入一个整数:" );
scanf ("%d" , &m);
while (m > 0 )
{
a = m%10 ;
printf (" %d" , a);
m = m/10 ;
}
system("pause" );
return 0 ;
}
4.输出两个int(32位)整数的二进制表中,有多少位(bit)不同
int main()
{
int m = 0 ;
int n = 0 ;
int i = 0 ;
int count = 0 ;
scanf("%d %d " , &m , &n);
m = m ^ n;
for (i = 0 ; i < 32 ; i++)
{
if (((m >>i)&1 ) == 1 )
count++;
}
printf ("不同位有%d \n" , count);
system ("pause" );
return 0 ;
}