dec to binary code example
Example 1: 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 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();