第 15 章 位操作(binbit)

 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('\n');
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] = '\0';
42 
43     return ps;
44 }
45 
46 //以4位为一组,显示二进制字符串
47 void show_bstr(const char *str)
48 {
49     int i = 0;
50     while (str[i])        //不是空字符
51     {
52         fputc(str[i], stdout);
53 
54         if (++i % 4 == 0 && str[i])
55             fputc(' ', stdout);
56     }
57 }
binbit.c

posted @ 2018-06-21 10:13  web1013  阅读(127)  评论(0编辑  收藏  举报