Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created August 4, 2014 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitcpf/525dec151918061e350b to your computer and use it in GitHub Desktop.
Save bitcpf/525dec151918061e350b to your computer and use it in GitHub Desktop.
public class Q5_2 {
public static void main(String[] args){
System.out.println(ToBinary(0.72,0));
System.out.println(ToBinary(0.87948723,0));
}
public static String ToBinary(double current, int bits){
if(current > 1 || current<0){
return "ERROR";
}
StringBuilder result = new StringBuilder();
if(current == 0.5 && bits < 32) {
result.append('1');
}
else if (current > 0.5){
if(bits > 32){
result.append("Error");
}
else {
result.append("1");
double temp = (current -0.5)*2;
String tempstring = ToBinary(temp,bits+1);
result.append(tempstring);
}
}
else{
if(bits > 32){
result.append("t");
return result.toString();
}
else{
result.append("0");
double temp = current*2;
String tempstring = ToBinary(temp,bits+1);
result.append(tempstring);
}
}
if(result.toString().contains("Error")){
return "Error";
}
else{
String rettemp = result.toString();
if(rettemp.contains("t")){
return rettemp.replace("t", "");
}
else{
return rettemp;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment