将数字以二进制的形式打印出来
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; } } }
如果你感兴趣,你可以把你妹妹介绍给我