Tuesday 11 July 2017

Java Code to convert decimal number to BCD representation.

Problem:

Design an algorithm that accepts as input a decimal number and converts it to the binary-coded decimal (bcd) representation. In the bcd scheme each digit is represented by a 4-digit binary code.

Solution:

package com.myprograms;

import java.util.Scanner;

public class BCD {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter decimal value");
int n = s.nextInt();
String bcd = "";
while(n != 0){
int r = n%10;
String temp = Integer.toBinaryString(r);
while(temp.length() < 4){
temp = "0" + temp;
}
bcd = temp + bcd;
n = n/10;
}
System.out.println("the bcd number is :" + bcd);
}
}


Output:

enter decimal value
67
the bcd number is :01100111


enter decimal value
194
the bcd number is :000110010100


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...