zoukankan      html  css  js  c++  java
  • c语言中将一个十进制数按照二进制输出

    c语言中将一个十进制数按照二进制输出

    1、

    #include <stdio.h>
    
    int main(void)
    {
        int bits = 0;
        unsigned tmp = ~0U;
        while(tmp)
        {
            if(tmp & 1U)
                bits++;
            tmp >>= 1;
        }
        
        int i;
        unsigned x;
        puts("please input a decimal number.");
        printf("x = "); scanf("%u", &x);
        
        for(i = bits - 1; i >= 0; i--)
        {
            putchar(x >> i & 1U ? '1' : '0');
        }
        putchar('
    ');
        
        return 0;
    }

    2、

    #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)
    {
        int i;
        for(i = int_bits() - 1; i >= 0; i--)
        {
            putchar((x >> i & 1U) ? '1' : '0');  
        }
        putchar('
    ');
    }
    
    int main(void)
    {
        unsigned a;
        puts("please input a decimal number.");
        printf("a = "); scanf("%u", &a);
        
        printf("
    binary a          = "); print_bits(a);
        return 0;
    }

    3、

    #include <stdio.h>
    
    int count_bits(void)
    {
        int bits = 0;
        unsigned x = ~0U;
        while(x)
        {
            if(x & 1U)
                bits++;
            x >>= 1;
        } 
        return bits;
    }
    
    int print_bits(unsigned x)
    {
        int i;
        for(i = count_bits() - 1; i >= 0; i--)
        {
            putchar((x >> i & 1U) ? '1' : '0');
        }
        putchar('
    ');
    }
    
    int main(void)
    {
        unsigned a;
        puts("please input an decimal number.");
        printf("a = "); scanf("%u", &a);
        
        printf("
    binary a     = ");  print_bits(a);
        return 0;
    }

  • 相关阅读:
    Buildroot构建指南--Overview
    监控摄像机常识:宽动态 (WDR)介绍和理解
    HM visual studio编译报错
    宽带有哪几种接入方式
    V.24 V.35 ISDN E1 POS这些常见的广域网接口
    Linux ppp 数据收发流程
    ppp协议解析二
    PPP协议解析一
    TAP/TUN(二)
    TAP/TUN浅析
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14792290.html
Copyright © 2011-2022 走看看