1 /*------------------------------------ 2 binbit.c -- 使用位操作显示二进制 3 ------------------------------------*/ 4 5 #include <stdio.h> 6 #include <limits.h> //提供 CHAR_BIT 的定义,CHAR_BIT 表示每字节的位数 7 8 char* itobs(int, char*); 9 void show_bstr(const char*); 10 11 int main() 12 { 13 char bin_str[CHAR_BIT * sizeof(int) + 1]; 14 int number; 15 16 puts("Enter integers and see them in binary."); 17 puts("Non-numeric input terminates program"); 18 19 while (scanf("%d", &number) == 1) 20 { 21 itobs(number, bin_str); 22 23 printf("%d is ", number); 24 25 show_bstr(bin_str); 26 27 putchar(' '); 28 } 29 30 puts("Bye"); 31 32 return 0; 33 } 34 35 char* itobs(int n, char *ps) 36 { 37 const static int size = CHAR_BIT * sizeof(int); 38 39 for (int i(size - 1); i >= 0; --i, n >>= 1) 40 ps[i] = (01 & n) + '0'; 41 ps[size] = '