Elian ten Holder
Elian ten Holder

Reputation: 362

Big Hex to binary

I have looked at a lot of post here on stackoverflow concerning this problem, I have found partial solutions but so far I have yet to find a solution that works for me. new BigDecimal("3324679375210329505").toString(2); Seems to work best for me (from: Convert a large 2^63 decimal to binary) but I do need leading and trailing zeros. Is there anyway I can convert a large (bigger than a long) hex to a binary (String) representation?

Thanks in advance.

Upvotes: 2

Views: 1136

Answers (2)

Bohemian
Bohemian

Reputation: 424993

The BigInteger class handles arbitrarily large numbers.

Trailing zeroes are allready handled. To handle leading zeroes, simply add a "1" at the front, which ensures a leading "1" bit, then strip it back off again:

String bits = new BigInteger("1" + hex, 16).toStting(2).substring(1);

Upvotes: 3

jlordo
jlordo

Reputation: 37813

You need leading zeroes? I don't know of a built-in function, but you can easily implement it yourself:

public static String hex2binary(String hex) {
    StringBuilder result = new StringBuilder(hex.length() * 4);
    for (char c : hex.toUpperCase().toCharArray()) {
        switch (c) {
        case '0': result.append("0000"); break;
        case '1': result.append("0001"); break;
        case '2': result.append("0010"); break;
        case '3': result.append("0011"); break;
        case '4': result.append("0100"); break;
        case '5': result.append("0101"); break;
        case '6': result.append("0110"); break;
        case '7': result.append("0111"); break;
        case '8': result.append("1000"); break;
        case '9': result.append("1001"); break;
        case 'A': result.append("1010"); break;
        case 'B': result.append("1011"); break;
        case 'C': result.append("1100"); break;
        case 'D': result.append("1101"); break;
        case 'E': result.append("1110"); break;
        case 'F': result.append("1111"); break;
        default: throw new IllegalArgumentException("Invalid hex: '" + hex + "'");
        }
    }
    return result.toString();
}

Upvotes: 2

Related Questions