Example 1: how to convert decimal to binary python
a = 5
#this prints the value of "a" in binary
print(bin(a))
Example 2: 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();
}
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 3: decimal to binary
import java.util.*;
public class DecimalToBinary {
public static void main(String[] args) {
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: 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 5: 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 6: 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;
}