1 /*------------------------------------ 2 invert4.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 int invert_end(int num, int bits); 11 12 int main() 13 { 14 char bin_str[CHAR_BIT * sizeof(int) + 1]; 15 int number; 16 17 puts("Enter integers and see them in binary."); 18 puts("Non-numeric input terminates program"); 19 20 while (scanf("%d", &number) == 1) 21 { 22 itobs(number, bin_str); 23 24 printf("%d is ", number); 25 26 show_bstr(bin_str); 27 28 putchar(' '); 29 30 number = invert_end(number, 4); 31 32 printf("Inverting the last 4 bits gives "); 33 34 show_bstr(itobs(number, bin_str)); 35 36 putchar(' '); 37 } 38 39 puts("Bye"); 40 41 return 0; 42 } 43 44 char* itobs(int n, char *ps) 45 { 46 const static int size = CHAR_BIT * sizeof(int); 47 48 for (int i(size - 1); i >= 0; --i, n >>= 1) 49 ps[i] = (01 & n) + '0'; 50 51 ps[size] = '