Двоичное представление данного числа

Опубликовано: 21 Января, 2022

Напишите программу для печати двоичного представления заданного числа.

Рекомендуется: сначала решите эту проблему на «ПРАКТИКЕ», прежде чем переходить к решению.

Источник: Microsoft Interview Set-3.

Метод 1: Итерационный
Для любого числа мы можем проверить, равен ли его i-й бит 0 (ВЫКЛ) или 1 (ВКЛ), выполняя побитовое И с помощью «2 ^ i» (2 увеличивается до i).

 1) Возьмем число 'ЧИСЛО', и мы хотим проверить, включен он или выключен 0-й бит.    
    бит = 2 ^ 0 (0-й бит)
    если NUM & bit == 1 означает, что 0-й бит включен, иначе 0-й бит выключен

2) Аналогично, если мы хотим проверить, включен ли 5-й бит или нет    
    бит = 2 ^ 5 (5-й бит)
    если NUM & bit == 1 означает, что его 5-й бит включен, иначе 5-й бит выключен.

Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

C++

// C++ Program for the binary
// representation of a given number
#include <bits/stdc++.h>
using namespace std;
 
  void bin(long n)
  {
    long i;
    cout << "0";
    for (i = 1 << 30; i > 0; i = i / 2)
    {
      if((n & i) != 0)
      {
        cout << "1";
      }
      else
      {
        cout << "0";
      }
    }
  }
 
// Driver Code
int main(void)
{
    bin(7);
    cout << endl;
    bin(4);
}
 
// This code is contributed by souravghosh0416

C

#include<stdio.h>
void bin(unsigned n)
{
    unsigned i;
    for (i = 1 << 31; i > 0; i = i / 2)
        (n & i) ? printf("1") : printf("0");
}
 
int main(void)
{
    bin(7);
    printf(" ");
    bin(4);
}

Java

public class GFG
{
  static void bin(long n)
  {
    long i;
    System.out.print("0");
    for (i = 1 << 30; i > 0; i = i / 2)
    {
      if((n & i) != 0)
      {
        System.out.print("1");
      }
      else
      {
        System.out.print("0");
      }
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    bin(7);
    System.out.println();
    bin(4);
  }
}
 
// This code is contributed by divyesh072019.

Python3

def bin(n) :
     
    i = 1 << 31
    while(i > 0) :
     
        if((n & i) != 0) :
         
            print("1", end = "")
         
        else :
            print("0", end = "")
             
        i = i // 2
             
bin(7)
print()
bin(4)
 
# This code is contributed by divyeshrabadiya07.

C#

using System;
 
public class GFG{
    static void bin(long n)
    {
        long i;
        Console.Write("0");
        for (i = 1 << 30; i > 0; i = i / 2)
        {
            if((n & i) != 0)
            {
                Console.Write("1");
            }
            else
            {
                Console.Write("0");
            }
        }
    }
    // Driver code
    static public void Main (){
        bin(7);
        Console.WriteLine();
        bin(4);
    }
}
// This code is contributed by avanitrachhadiya2155

Javascript

<script>
// JavaScript Program for the binary
// representation of a given number
    function bin(n)
    {
        let i;
        document.write("0");
        for (i = 1 << 30; i > 0; i = Math.floor(i/2))
        {
            if((n & i) != 0)
            {
                document.write("1");
            }
            else
            {
                document.write("0");
            }
        }
    }
     
    bin(7);
    document.write("<br>");
    bin(4);
     
     
    // This code is contributed by rag2127
     
</script>
Output

00000000000000000000000000000111
00000000000000000000000000000100