您的位置:首页 > 其它

将数字以二进制的形式打印出来

2016-09-14 10:00 204 查看
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('\n');
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐