Thursday, 5 September 2013

Given a float number, convert it into the string WITHOUT using any inbuilt function/library.

Implementation

class BinaryRepreOfRealNumberEx{
//function to convert integer into binary format
//Example : Input 2
//         Output : 10
public static String convertIntegerIntoBinaryFormat(int n){
StringBuffer binary = new StringBuffer();
while(n > 0){
binary.append( n & 1);
n = n >> 1;
}
binary.reverse();
return new String(binary);
}

//function to convert double into binary format
public static String convertDoubleIntoBinaryFormat(double n){
if(n >= 1 || n <= 0 )
return "error";

StringBuilder result = new StringBuilder();
result.append(".");

while(n > 0){
double r = n*2;
if(r >= 1){
result.append(1);
n = r - 1;
}else{
result.append(0);
n = r;
}
}
return result.toString();
}

//function to convert number into binary format
public static String convertIntoBinaryFormat(double number){
int t = (int)number;
String intPart = binary(t);

double d = number - t;
String doublePart = printBinary(d);

return intPart + doublePart;
}

public static void main(String []args){
String result = "";
double n = 2.2;

result = convertIntoBinaryFormat(n);
System.out.println("Binary Representation of "+ n +" "+result );
}
}

No comments:

Post a Comment