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();
}
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++
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int>nums;
int num = 0;
cout<<"Number: "<<endl;
cin>>num;
int i=0;
while(num!=0)
{
nums.push_back(num%2);
i++;
num=num/2;
}
reverse(nums.begin(),nums.end());
for(auto x:nums)
{
cout<<x;
}
return 0;
}
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: 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();