c语言中将一个十进制数按照二进制输出
c语言中将一个十进制数按照二进制输出
1、
#include <stdio.h> int main(void) { int bits = 0; unsigned tmp = ~0U; while(tmp) { if(tmp & 1U) bits++; tmp >>= 1; } int i; unsigned x; puts("please input a decimal number."); printf("x = "); scanf("%u", &x); for(i = bits - 1; i >= 0; i--) { putchar(x >> i & 1U ? '1' : '0'); } putchar('\n'); return 0; }
2、
#include <stdio.h> int count_bits(unsigned x) { int bits = 0; while(x) { if(x & 1U) bits++; x >>= 1; } return bits; } int int_bits(void) { return count_bits(~0U); } int print_bits(unsigned x) { int i; for(i = int_bits() - 1; i >= 0; i--) { putchar((x >> i & 1U) ? '1' : '0'); } putchar('\n'); } int main(void) { unsigned a; puts("please input a decimal number."); printf("a = "); scanf("%u", &a); printf("\nbinary a = "); print_bits(a); return 0; }
3、
#include <stdio.h> int count_bits(void) { int bits = 0; unsigned x = ~0U; while(x) { if(x & 1U) bits++; x >>= 1; } return bits; } int print_bits(unsigned x) { int i; for(i = count_bits() - 1; i >= 0; i--) { putchar((x >> i & 1U) ? '1' : '0'); } putchar('\n'); } int main(void) { unsigned a; puts("please input an decimal number."); printf("a = "); scanf("%u", &a); printf("\nbinary a = "); print_bits(a); return 0; }