decimal to binary converter code example

Example 1: convert decimal to binary in java

public class DecimalToBinaryExample2{    
public static void toBinary(int decimal){    
     int binary[] = new int[40];    
     int index = 0;    
     while(decimal > 0){    
       binary[index++] = decimal%2;    
       decimal = decimal/2;    
     }    
     for(int i = index-1;i >= 0;i--){    
       System.out.print(binary[i]);    
     }    
System.out.println();//new line  
}    
public static void main(String args[]){      
System.out.println("Decimal of 10 is: ");  
toBinary(10);    
System.out.println("Decimal of 21 is: ");  
toBinary(21);    
System.out.println("Decimal of 31 is: ");    
toBinary(31);  
}}

Example 2: how to do decimal to binary converdsion in c++

// C++ program for decimal to binary 

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>


using namespace std; 

int main() {

    vector<int>nums; // list that will hold binary values

    int num = 0; 
    cout<<"Number: "<<endl;
    cin>>num; // number input 
    int i=0; // iterator for vector

    while(num!=0)
    {
        nums.push_back(num%2); // adds binary value to the back of string 
        i++; // i gets incremented for the next position in vector 
        num=num/2; 
    }
 
    reverse(nums.begin(),nums.end()); // reverses order of vector 
  
    for(auto x:nums)
    {
        cout<<x; // outputs stuff in vector 
    }
  return 0; 
}

Example 3: decimal to binary

//Java Solution for Decimal To Binary Conversion

import java.util.*;
public class DecimalToBinary {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int dec = sc.nextInt();
		StringBuffer sb = new StringBuffer();
		while(dec!=0)
		{
			sb.append(dec%2);
			dec=dec/2;
		}
		System.out.println(sb.reverse());
		
	}

}

Example 4: decimal to binary

# Python program to convert decimal to binary
   
# Function to convert Decimal number
# to Binary number
def decimalToBinary(n):
    return bin(n).replace("0b", "")
   
# Driver code
if __name__ == '__main__':
    print(decimalToBinary(8))
    print(decimalToBinary(18))
    print(decimalToBinary(7))

Example 5: decimal to binary

#include <iostream>
#include <stdlib.h>

int main ()
{
    int i;
    char buffer [33];
    printf ("Enter a number: ");
    scanf ("%d",&i);
    itoa (i,buffer,10);
    printf ("decimal: %s\n",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s\n",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s\n",buffer);
    return 0;
}

Example 6: decimal to binary

std::string binary = std::bitset<8>(n).to_string();

Tags:

Cpp Example