给一个10进制数,如何输出2进制数中1的个数?
给一个10进制数,如何输出2进制数中1的个数?
第一眼看起来觉得好容易,但仔细想想你这个十进制数没有限定正,负,整数,浮点数,小白的我表示无力啊!!
等大神!!!
#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编辑过]
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; }