Aug 16, 2011
Aug 16, 2011
N/A Views
MD
warning
この記事は2年以上前に更新されたものです。情報が古くなっている可能性があります。

public static String toBinaryString(double d) {
int intPart = (int) d;
double decPart = d - intPart;

    String intStr = "";
    while (intPart > 0) {
        int b = intPart % 2;
        intPart >>= 1;
        intStr = b + intStr;
    }
    StringBuilder s = new StringBuilder();
    while (decPart > 0) {
        if (s.length() > 32) {
            return "ERROR";
        }

        if (decPart == 1) {
            s.append(1);
            break;
        }
        double b = decPart * 2;
        if (b >= 1) {
            s.append(1);
            decPart = b - 1;
        } else {
            s.append(0);
            decPart = b;
        }
    }
    return intStr + "." + s.toString();
}

11.75 -> 1011.11

Found a mistake? Update the entry.
Share this article: