给一个10进制数,如何输出2进制数中1的个数?
给一个10进制数,如何输出2进制数中1的个数?
2015-10-19 20:52
2015-10-20 03:04
程序代码:
#include <stdio.h>
#include <conio.h>
void Show_Byte(unsigned char ch)
{
char buffer[8];
unsigned char mask = 1;
for (size_t index = sizeof(buffer); index > 0; --index)
{
buffer[index - 1] = ((ch & mask) == mask) + '0';
mask <<= 1;
}
for (size_t index = 0; index < sizeof(buffer); ++index)
{
putchar(buffer[index]);
}
}
int main()
{
unsigned char* p;
int a = 1000;
p = (unsigned char*)&a;
for (size_t index = 0; index < sizeof(a); ++index)
{
Show_Byte(*p++);
putchar(' ');
}
putchar('\n');
double b = 1000;
p = (unsigned char*)&b;
for (size_t index = 0; index < sizeof(b); ++index)
{
Show_Byte(*p++);
putchar(' ');
}
putchar('\n');
float c = 1000;
p = (unsigned char*)&c;
for (size_t index = 0; index < sizeof(c); ++index)
{
Show_Byte(*p++);
putchar(' ');
}
putchar('\n');
_getch();
return 0;
}
[此贴子已经被作者于2015-10-20 04:36编辑过]

2015-10-20 04:17
程序代码:uint32_t func( uint32_t x )
{
x = (x & 0x55555555UL) + ((x >> 1) & 0x55555555UL);
x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
x = (x & 0x0f0f0f0fUL) + ((x >> 4) & 0x0f0f0f0fUL);
x = (x & 0x00ff00ffUL) + ((x >> 8) & 0x00ff00ffUL);
x = (x & 0x0000ffffUL) + ((x >> 16) & 0x0000ffffUL);
return x;
}
2015-10-21 12:29
2015-10-21 16:18
2015-10-22 10:30
2015-10-22 12:20