Write a program to print Binary representation of a given number.
Source: Microsoft Interview Set-3
Method 1: Iterative
For any number, we can check whether its ‘i’th bit is 0(OFF) or 1(ON) by bitwise ANDing it with “2^i” (2 raise to i).
1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF
bit = 2 ^ 0 (0th bit)
if NUM & bit >= 1 means 0th bit is ON else 0th bit is OFF
2) Similarly if we want to check whether 5th bit is ON or OFF
bit = 2 ^ 5 (5th bit)
if NUM & bit >= 1 means its 5th bit is ON else 5th bit is OFF.
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++
#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" ;
}
}
}
int main( void )
{
bin(7);
cout << endl;
bin(4);
}
|
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 ( "\n" );
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" );
}
}
}
public static void main(String[] args)
{
bin( 7 );
System.out.println();
bin( 4 );
}
}
|
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 )
|
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" );
}
}
}
static public void Main (){
bin(7);
Console.WriteLine();
bin(4);
}
}
|
Javascript
<script>
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);
</script>
|
Output
00000000000000000000000000000111
00000000000000000000000000000100
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2: Recursive
Following is recursive method to print binary representation of ‘NUM’.
step 1) if NUM > 1
a) push NUM on stack
b) recursively call function with 'NUM / 2'
step 2)
a) pop NUM from stack, divide it by 2 and print it's remainder.
C++
#include <bits/stdc++.h>
using namespace std;
void bin(unsigned n)
{
if (n > 1)
bin(n / 2);
cout << n % 2;
}
int main( void )
{
bin(7);
cout << endl;
bin(4);
}
|
C
void bin(unsigned n)
{
if (n > 1)
bin(n / 2);
printf ( "%d" , n % 2);
}
int main( void )
{
bin(7);
printf ( "\n" );
bin(4);
}
|
Java
class GFG {
static void bin( int n)
{
if (n > 1 )
bin(n / 2 );
System.out.print(n % 2 );
}
public static void main(String[] args)
{
bin( 7 );
System.out.println();
bin( 4 );
}
}
|
Python3
def bin (n):
if n > 1 :
bin (n / / 2 )
print (n % 2 , end = "")
if __name__ = = "__main__" :
bin ( 7 )
print ()
bin ( 4 )
|
C#
using System;
class GFG {
static void bin( int n)
{
if (n > 1)
bin(n / 2);
Console.Write(n % 2);
}
static public void Main()
{
bin(7);
Console.WriteLine();
bin(4);
}
}
|
PHP
<?php
function bin( $n )
{
if ( $n > 1)
bin( $n /2);
echo ( $n % 2);
}
bin(7);
echo ( "\n" );
bin(4);
?>
|
Javascript
<script>
function bin(n)
{
if (n > 1)
bin(parseInt(n / 2, 10));
document.write(n % 2);
}
bin(7);
document.write( "</br>" );
bin(4);
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Method 3: Recursive using bitwise operator
Steps to convert decimal number to its binary representation are given below:
step 1: Check n > 0
step 2: Right shift the number by 1 bit and recursive function call
step 3: Print the bits of number
C++
#include <bits/stdc++.h>
using namespace std;
void bin(unsigned n)
{
if (n > 1)
bin(n >> 1);
printf ( "%d" , n & 1);
}
int main( void )
{
bin(131);
printf ( "\n" );
bin(3);
return 0;
}
|
Java
class GFG {
static void bin(Integer n)
{
if (n > 1 )
bin(n >> 1 );
System.out.printf( "%d" , n & 1 );
}
public static void main(String[] args)
{
bin( 131 );
System.out.printf( "\n" );
bin( 3 );
}
}
|
Python3
def bin (n):
if (n > 1 ):
bin (n >> 1 )
print (n & 1 , end = "")
bin ( 131 )
print ()
bin ( 3 )
|
C#
using System;
public class GFG {
static void bin( int n)
{
if (n > 1)
bin(n >> 1);
Console.Write(n & 1);
}
public static void Main()
{
bin(131);
Console.WriteLine();
bin(3);
}
}
|
PHP
<?php
function bin( $n )
{
if ( $n > 1)
bin( $n >>1);
echo ( $n & 1);
}
bin(131);
echo "\n" ;
bin(3);
|
Javascript
<script>
function bin(n)
{
if (n > 1)
bin(n >> 1);
document.write(n & 1);
}
bin(131);
document.write( "<br>" );
bin(3);
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Method 4: Using Bitset of C++
We can use the bitset class of C++ to store the binary representation of any number (positive as well as a negative number). It offers us the flexibility to have the number of bits of our desire, like whether we want to have 32-bit binary representation of just an 8-bit representation of a number.
A complete guide to using bitset can be found on this gfg article LINK.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 5, m = -5;
bitset<8> b(n);
bitset<8> b1(m);
cout << "Binary of 5:" << b << endl;
cout << "Binary of -5:" << b1 << endl;
return 0;
}
|
Java
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
int n = 5 ;
int m = - 5 ;
String b = new BigInteger(Integer.toString(n))
.toString( 2 );
String b1 = Integer.toBinaryString(m & 0xFF );
b = String.format( "%8s" , b).replace( ' ' , '0' );
b1 = String.format( "%8s" , b1).replace( ' ' , '0' );
System.out.println( "Binary of 5: " + b);
System.out.println( "Binary of -5: " + b1);
}
}
|
Python3
import sys
n = 5
m = - 5
b = bin (n & int ( "1" * 8 , 2 ))[ 2 :].zfill( 8 )
b1 = bin (m & int ( "1" * 8 , 2 ))[ 2 :].zfill( 8 )
print ( "Binary of 5:" , b)
print ( "Binary of -5:" , b1)
|
C#
using System;
using System.Collections;
namespace BitArrayExample {
class Program {
static void Main( string [] args)
{
int n = 5;
int m = -5;
BitArray b = new BitArray( new int [] { n });
BitArray b1 = new BitArray( new int [] { m });
Console.WriteLine( "Binary of 5:" + GetBits(b));
Console.WriteLine( "Binary of -5:" + GetBits(b1));
Console.ReadLine();
}
private static string GetBits(BitArray bits)
{
System.Text.StringBuilder sb
= new System.Text.StringBuilder();
for ( int i = 0; i < 8; i++) {
char c = bits[i] ? '1' : '0' ;
sb.Insert(0, c);
}
return sb.ToString();
}
}
}
|
Javascript
let val1 = 5;
let val2 = -5;
let binary1 = (val1 & parseInt( "1" .repeat(8), 2)).toString(2);
let binary2 = (val2 & parseInt( "1" .repeat(8), 2)).toString(2);
let output1 = "0" .repeat(8 - binary1.length) + binary1;
let output2 = "0" .repeat(8 - binary2.length) + binary2;
console.log( "Binary of 5:" + output1);
console.log( "Binary of -5:" + output2);
|
Output
Binary of 5:00000101
Binary of -5:11111011
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 5: Using Inbuilt library:
C++
#include <bits/stdc++.h>
using namespace std;
void binary( int num){
cout << bitset<32>(num).to_string().substr(32 - log2(num));
}
int main()
{
int x = 10;
binary(x);
}
|
Java
import java.util.*;
class GFG {
static void binary( int num){
System.out.println( "the binary number is : " + Integer.toString(num, 2 ));
}
public static void main(String[] args)
{
int x = 10 ;
binary(x);
}
}
|
Python3
def binary(num):
return int ( bin (num).split( '0b' )[ 1 ])
if __name__ = = "__main__" :
x = 10
binary_x = binary(x)
print ( "the binary number is :" ,binary_x)
|
C#
using System;
class GFG{
static void binary( int num){
Console.WriteLine( "the binary number is : " + Convert.ToString(num,2));
}
public static void Main(String[] args)
{
int x = 10;
binary(x);
}
}
|
Javascript
const number = 10;
const Binary_Number = number.toString(2);
console.log( "the binary number is : " + Binary_Number);
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Video tutorial
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
This article is compiled by Narendra Kangralkar.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!