Search This Blog

Showing posts with label BCD representation. Show all posts
Showing posts with label BCD representation. Show all posts

Decimal to BCD Converter in Java

In this post,we will see java program to convert decimal number to BCD representation. Binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of bits, usually four. Thus the decimal digit 1 corresponds to  0001, 2 corresponds to 0010,....  8 corresponds to 1000 and 9 corresponds to 1001. Therefore, decimal number 194 can be represented in BCD as 0001 1001 0100. It should be noted that 1010, 1011, 1100, 1101,1110 and 1111 are illegal in BCD. The following java program converts any decimal number to BCD. But in this program, for conversion each digit in the decimal, we use Integer.toBinaryString() method. So, i have added another program which does not use this method.

Program 1:


    public static String toBCD(int num)
    {
        String BCD="";
        while(num!=0)
        {
        int t=num%10;
        String tBCD=Integer.toBinaryString(t);
        while(tBCD.length()<4)
            {
            tBCD="0"+tBCD;
            }
        BCD=tBCD+BCD;
        num/=10;
        }
        return BCD;
    }


Program 2:


import java.util.Scanner;
public class DecimalToBCD {

static String digitToBcd(int digit)
{
    String str="";
    for(int i=3;i>=0;i--)
        {
        int d=(int) Math.pow(2,i);
        if(digit/d!=0)
            {
                str+="1";
                digit-=d;
            }
        else
            str+="0";
        }
    return str;
}
    
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int decimal=sc.nextInt();
        int digit;
        String BCD="";
        while(decimal!=0)
            {
            digit=decimal%10;
            BCD=digitToBcd(digit)+" "+BCD;
            decimal/=10;
            }
        System.out.println("BCD is:"+BCD);
        
    }
}


The second program does not use any built in methods for conversion of decimal to BCD.