Skip to content

Instantly share code, notes, and snippets.

@iwilbert
Created August 3, 2014 21:49
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 iwilbert/b562f5d2cdb8ba0f8af5 to your computer and use it in GitHub Desktop.
Save iwilbert/b562f5d2cdb8ba0f8af5 to your computer and use it in GitHub Desktop.
public static String toBinary(double num) {
if (num >= 1 || num < 0) {
return "ERROR";
}
StringBuffer sb = new StringBuffer();
sb.append("0.");
int i;
for (i = 0; i < 32 && num != 0; i++) {
if (num >= 0.5) {
sb.append(1);
num -= 0.5;
} else
sb.append(0);
num *= 2;
}
if (i == 32 && num != 0)
return "ERROR";
else
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment