convert from decimal 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: binary to decimal

double binaryToDecimal(char binary[DIM]) {
	char binary2[DIM] = "", floa[DIM] = "";
	double decimal = 0, negDec = 0, flo = 0;
	int count = 0, j = 0, i = 0, f = 0, g = 0, h = 0, count1 = 0, d = 0, k = 0;
	while (binary[d] != '\0'&&binary[d] != '.') { d++; }
	d--;
	if (binary[0] == '-') {
		while (binary[k] != '\0') {
			binary[k] = binary[k + 1];
			k++;
		}
		k = 0;
		while (binary[k] == '0') {
			d--;
			k++;
		}
		negDec = pot(2.000, d*1.000, 1);
	}
	while (binary[i] != '\0'&&binary[i] != '.') {
		i++;
	}
	i--;
	count = i;
	h = i;
	while (binary[h] != '\0') {
		floa[g] = binary[h + 2];
		g++;
		h++;
	}
	g--;
	count1 = g;
	while (i >= 0) {
		binary2[j] = binary[i];
		i--;
		j++;
	}
	binary2[j] = '\0';
	while (i <= count) {
		if (binary2[i] == '1') {
			decimal = decimal + pot(2.000, i, 1);
		}
		i++;
	}
	h = -1;
	g = 0;
	while (g <= count1) {
		if (floa[g] == '1') {
			flo = flo + pot(2.000, h, 1);
		}
		g++;
		h--;
	}
	decimal = decimal + flo;
	if (negDec > 0) {
		decimal = (decimal - negDec);
		if (flo > 0) {
			double f = fl(decimal);
			f = 1 - f;
			decimal = returnDeciPart(decimal) - f;
		}
	}
	return decimal;
}

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

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

Example 5: decimal to binary

#include 
#include 

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;
}

Tags:

Misc Example