convert number to binary code example

Example 1: 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 2: 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 3: 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 4: decimal to binary

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

Example 5: binary to decimal

import java.util.Scanner;

public class BinaryToDecimal {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String binary = sc.next();
		// This is one line solution for binary to decimal in java
		System.out.println(Integer.parseInt(binary,2));
		
		//This solution is based on formula for binary to decimal conversion
		int n=0,dec=0;
		for(int i=binary.length()-1;i>=0;i--)
		{
			dec = dec + Integer.parseInt(String.valueOf(binary.charAt(i)))*(int)Math.pow(2,n);
			n++;
		}
		System.out.println(dec);

	}

}

Example 6: binary to decimal

= (11001010)2
= 1x27+1x26+0x25+0x24+1x23+0x22+1x21+0x20
= 128+64+0+0+8+0+2+0
= (202)10

Tags:

Java Example