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++
// C++ Program for the binary
// representation of a given number
#include <bits/stdc++.h>
usingnamespacestd;
voidbin(longn)
{
longi;
cout << "0";
for(i = 1 << 30; i > 0; i = i / 2)
{
if((n & i) != 0)
{
cout << "1";
}
else
{
cout << "0";
}
}
}
// Driver Code
intmain(void)
{
bin(7);
cout << endl;
bin(4);
}
// This code is contributed by souravghosh0416
C
#include<stdio.h>
voidbin(unsigned n)
{
unsigned i;
for(i = 1 << 31; i > 0; i = i / 2)
(n & i) ? printf("1") : printf("0");
}
intmain(void)
{
bin(7);
printf("\n");
bin(4);
}
Java
publicclassGFG
{
staticvoidbin(longn)
{
longi;
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
publicstaticvoidmain(String[] args)
{
bin(7);
System.out.println();
bin(4);
}
}
// This code is contributed by divyesh072019.
Python3
defbin(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#
usingSystem;
publicclassGFG{
staticvoidbin(longn)
{
longi;
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
staticpublicvoidMain (){
bin(7);
Console.WriteLine();
bin(4);
}
}
// This code is contributed by avanitrachhadiya2155
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++
// C++ Program for the binary
// representation of a given number
#include <bits/stdc++.h>
usingnamespacestd;
voidbin(unsigned n)
{
/* step 1 */
if(n > 1)
bin(n / 2);
/* step 2 */
cout << n % 2;
}
// Driver Code
intmain(void)
{
bin(7);
cout << endl;
bin(4);
}
// This code is contributed
// by Akanksha Rai
C
// C Program for the binary
// representation of a given number
voidbin(unsigned n)
{
/* step 1 */
if(n > 1)
bin(n / 2);
/* step 2 */
printf("%d", n % 2);
}
// Driver Code
intmain(void)
{
bin(7);
printf("\n");
bin(4);
}
Java
// Java Program for the binary
// representation of a given number
classGFG {
staticvoidbin(intn)
{
/* step 1 */
if(n > 1)
bin(n / 2);
/* step 2 */
System.out.print(n % 2);
}
// Driver code
publicstaticvoidmain(String[] args)
{
bin(7);
System.out.println();
bin(4);
}
}
// This code is contributed
// by ChitraNayal
Python3
# Python3 Program for the binary
# representation of a given number
defbin(n):
ifn > 1:
bin(n//2)
print(n %2, end="")
# Driver Code
if__name__ =="__main__":
bin(7)
print()
bin(4)
# This code is contributed by ANKITRAI1
C#
// C# Program for the binary
// representation of a given number
usingSystem;
classGFG {
staticvoidbin(intn)
{
// step 1
if(n > 1)
bin(n / 2);
// step 2
Console.Write(n % 2);
}
// Driver code
staticpublicvoidMain()
{
bin(7);
Console.WriteLine();
bin(4);
}
}
// This code is contributed ajit
PHP
<?php
// PHP Program for the binary
// representation of a given number
functionbin($n)
{
/* step 1 */
if($n> 1)
bin($n/2);
/* step 2 */
echo($n% 2);
}
// Driver code
bin(7);
echo("\n");
bin(4);
// This code is contributed
// by Shivi_Aggarwal
?>
Javascript
<script>
// Javascript program for the binary
// representation of a given number
functionbin(n)
{
// Step 1
if(n > 1)
bin(parseInt(n / 2, 10));
// Step 2
document.write(n % 2);
}
// Driver code
bin(7);
document.write("</br>");
bin(4);
// This code is contributed by divyeshrabadiya07
</script>
Output
111
100
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++
// C++ implementation of the approach
#include <bits/stdc++.h>
usingnamespacestd;
// Function to convert decimal
// to binary number
voidbin(unsigned n)
{
if(n > 1)
bin(n >> 1);
printf("%d", n & 1);
}
// Driver code
intmain(void)
{
bin(131);
printf("\n");
bin(3);
return0;
}
Java
// Java implementation of the approach
classGFG {
// Function to convert decimal
// to binary number
staticvoidbin(Integer n)
{
if(n > 1)
bin(n >> 1);
System.out.printf("%d", n & 1);
}
// Driver code
publicstaticvoidmain(String[] args)
{
bin(131);
System.out.printf("\n");
bin(3);
}
}
/*This code is contributed by PrinciRaj1992*/
Python3
# Python 3 implementation of above approach
# Function to convert decimal to
# binary number
defbin(n):
if(n > 1):
bin(n >> 1)
print(n & 1, end="")
# Driver code
bin(131)
print()
bin(3)
# This code is contributed by PrinciRaj1992
C#
// C# implementation of above approach
usingSystem;
publicclassGFG {
// Function to convert decimal
// to binary number
staticvoidbin(intn)
{
if(n > 1)
bin(n >> 1);
Console.Write(n & 1);
}
// Driver code
publicstaticvoidMain()
{
bin(131);
Console.WriteLine();
bin(3);
}
}
/*This code is contributed by PrinciRaj1992*/
PHP
<?php
// PHP implementation of the approach
// Function to convert decimal
// to binary number
functionbin($n)
{
if($n> 1)
bin($n>>1);
echo($n& 1);
}
// Driver code
bin(131);
echo"\n";
bin(3);
// This code is contributed
// by Akanksha Rai
Javascript
<script>
// JavaScript implementation of the approach
// Function to convert decimal
// to binary number
functionbin(n)
{
if(n > 1)
bin(n >> 1);
document.write(n & 1);
}
// Driver code
bin(131);
document.write("<br>");
bin(3);
// This code is contributed by Surbhi Tyagi.
</script>
Output
10000011
11
Time Complexity: O(log N) Auxiliary Space: O(log N)
Method 4:Using Bitset of C++
We can use thebitset 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>
usingnamespacestd;
intmain()
{
intn = 5, m = -5;
bitset<8> b(n);
bitset<8> b1(m);
cout << "Binary of 5:"<< b << endl;
cout << "Binary of -5:"<< b1 << endl;
return0;
}
Java
importjava.math.BigInteger;
importjava.util.Scanner;
publicclassMain {
publicstaticvoidmain(String[] args)
{
// Initialize two variables with values 5 and -5
intn = 5;
intm = -5;
// Use BigInteger to convert integers to binary
String b = newBigInteger(Integer.toString(n))
.toString(2);
String b1 = Integer.toBinaryString(m & 0xFF);
// Pad the binary strings with 0s to 8 bits
b = String.format("%8s", b).replace(' ', '0');
b1 = String.format("%8s", b1).replace(' ', '0');
// Printing the binary representation of n and m
System.out.println("Binary of 5: "+ b);
System.out.println("Binary of -5: "+ b1);
}
}
// This code is contributed by Vikram_Shirsat
Python3
# Importing the necessary module
importsys
# Initialize two variables with values 5 and -5
n =5
m =-5
# Using the format function to convert integers to binary
b =bin(n & int("1"*8, 2))[2:].zfill(8)
b1 =bin(m & int("1"*8, 2))[2:].zfill(8)
# Printing the binary representation of n and m
print("Binary of 5:", b)
print("Binary of -5:", b1)
# This code is contributed by Vikram_Shirsat
C#
usingSystem;
usingSystem.Collections;
namespaceBitArrayExample {
classProgram {
staticvoidMain(string[] args)
{
// Initialize two variables with values 5 and -5
intn = 5;
intm = -5;
// Pad the binary strings with 0s to 8 bits
BitArray b = newBitArray(newint[] { n });
BitArray b1 = newBitArray(newint[] { m });
// Printing the binary representation of n and m
Console.WriteLine("Binary of 5:"+ GetBits(b));
Console.WriteLine("Binary of -5:"+ GetBits(b1));
Console.ReadLine();
}
privatestaticstringGetBits(BitArray bits)
{
System.Text.StringBuilder sb
= newSystem.Text.StringBuilder();
for(inti = 0; i < 8; i++) {
charc = bits[i] ? '1': '0';
sb.Insert(0, c);
}
returnsb.ToString();
}
}
}
// This code is contributed by poojaagarwal2.
Javascript
// Initialize two variables with values 5 and -5
let val1 = 5;
let val2 = -5;
// Using the format function to convert integers to binary
let binary1 = (val1 & parseInt("1".repeat(8), 2)).toString(2);
let binary2 = (val2 & parseInt("1".repeat(8), 2)).toString(2);
// For generating the output size of length 8 binary digit
let output1 = "0".repeat(8 - binary1.length) + binary1;
let output2 = "0".repeat(8 - binary2.length) + binary2;
// Printing the binary representation of val1 and val2
System.out.println("the binary number is : "+ Integer.toString(num,2));
}
// Driver Code
publicstaticvoidmain(String[] args)
{
intx = 10;
binary(x);
}
}
// This code is contributed by sanjoy_62.
Python3
defbinary(num):
returnint(bin(num).split('0b')[1])
if__name__ =="__main__":
x =10
binary_x =binary(x)
print("the binary number is :",binary_x)
# This code is contributed by Rishika Gupta.
C#
// C# program for the above approach
usingSystem;
classGFG{
staticvoidbinary(intnum){
Console.WriteLine("the binary number is : "+ Convert.ToString(num,2));
}
// Driver Code
publicstaticvoidMain(String[] args)
{
intx = 10;
binary(x);
}
}
// This code is contributed by code_hunt.
Javascript
// JavaScript code for the above approach
const number = 10;
const Binary_Number = number.toString(2);
console.log("the binary number is : "+ Binary_Number);
// This code is contributed by sam
Output
1010
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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Please Login to comment...