c语言中输出十进制转换为二进制结果并指定显示的位数。
1、
#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, unsigned n) { int i = int_bits(); i = (n < i) ? n - 1 : i - 1; for(i; i >= 0; i--) { putchar((x >> i & 1U) ? '1' : '0'); } putchar(' '); } int main(void) { unsigned a, b; puts("please input two nonnegative integers."); printf("a = "); scanf("%u", &a); printf("b = "); scanf("%u", &b); unsigned x; puts("please input the units to show."); printf("x = "); scanf("%u", &x); printf("binary a = "); print_bits(a, x); printf("binary b = "); print_bits(b, x); return 0; }
}