the class Binary has two long variables bin and dec. void readBin() reads the number. what i didn't get is to write a recursive function long(convertDec(long) to convert bin to its decimal equivalent and print in function show()|||well i just wrote you two recursive functions to convert bin to dec and dec to bin. you should be able to handle rest, if u need more help leave additional notes and i will adjust the answer for you.
public class Binary {
public long convertDecToBin( long dec ){
if(dec==0 || dec==1){
return dec;
}
return Long.parseLong( convertDecToBinRecursive( dec));
}
private String convertDecToBinRecursive( long dec){
if( dec/2!=0){
return convertDecToBinRecursive( dec/2)+ dec%2;
}
return dec%2 + "";
}
public long convertBinToDec( long bin){
return convertBinToDecRecursive( bin,0);
}
private long convertBinToDecRecursive( long bin, int count){
long result = 0;
if( bin/10!=0){
result = convertBinToDecRecursive( bin/10, 1+count);
}
return (bin%10) * ((long) Math.pow(2, count)) + result;
}
public static void main(String[] args){
Binary binary = new Binary();
long bin = binary.convertDecToBin( 181);
long dec = binary.convertBinToDec( 10110101);
System.out.println( bin);
System.out.println( dec);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment