zoukankan      html  css  js  c++  java
  • 第 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('
    ');
    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] = '';
    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

  • 相关阅读:
    小学生二元四则运算(F)
    补进度条
    附加作业
    个人总结
    第四 五周结对作业(照片)
    第四,五周——Java编写的电梯模拟系统(结对作业)
    第三周(JAVA编写的 wordcount)
    第三周续(读代码)
    第三周
    第二周续.(代码)
  • 原文地址:https://www.cnblogs.com/web1013/p/9207471.html
Copyright © 2011-2022 走看看