zoukankan      html  css  js  c++  java
  • 将数字以二进制的形式打印出来

    C语言:

    // ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include "stdio.h"
    #include "limits.h"
    
    int count_bits(unsigned x)
    {
        unsigned int bits = 0;
    
        while (x)
        {
            if ((x & 1U))
                bits++;
        
            x >>= 1;
        }
            
    
        return bits;
    }
    
    int int_bits(void)
    {
        return count_bits(UINT_MAX);
    }
    
    
    void print_bits(unsigned x)
    {
        int i;
        for (i = int_bits() - 1; i >= 0; i--)
        {
            putchar(((x >> i) & 1U) ? '1' : '0');
        }
    }
    
    
    int main(void)
    {
        unsigned a, b;
        a = 1111111;
        b = 112222;
    
        print_bits(a);
        putchar('
    ');
        print_bits(b);
    
        
        scanf("%u", &a);
    }

    C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication4
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("位: " + GetCount());
    
                int value = 8888;
    
                for (int i = GetCount(); i > 0; i--)
                {
                    Console.Write(((value >> i) & 1) > 0 ? '1' : '0');
                }
    
    
                Console.ReadLine();
    
            }
    
            static int GetCount() 
            {
                int bits = 0;
                int max = int.MaxValue;
    
                while (max > 0) 
                {
                    if ((max & 1) >= 1) 
                    {
                        bits++;
                    }
    
                    max >>= 1;
                }
    
                return bits + 1;
            }
        }
    }
  • 相关阅读:
    php-beanstalkd消息队列类分享
    php curl抓取类分享
    df -i 100%时处理方法
    php生成红包
    PHP牛牛游戏算法
    Yii 框架不同逻辑处理方法统一事务处理
    Linux上web服务器搭建
    Linux 上pcntl安装步骤
    PHP错误级别设置
    day40 ,epoll,数据库相关概念
  • 原文地址:https://www.cnblogs.com/plateFace/p/5870823.html
Copyright © 2011-2022 走看看