javabinaryhexbase-conversion

Conversion from hex to binary keeping 8 bits in Java


I need to write in a 8x8 matrix the binary values of 8 hexadecimal numbers (one for row). Those numbers will be at the most 8 bits long. I wrote the following code to convert from hexadecimal to binary:

private String hexToBin (String hex){
    int i = Integer.parseInt(hex, 16);
    String bin = Integer.toBinaryString(i);
    return bin;

}

But I have the problem that values below 0x80 don't need 8 bits to be represented in binary. My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)? Thanks a lot


Solution

  • Hint: use string concatenation to add the appropriate number of zeros in the appropriate place.

    For example:

    public String hexToBin(String hex) throws NumberFormatException {
        String bin = Integer.toBinaryString(Integer.parseInt(hex, 16));
        int len = bin.length();
        return len == 8 ? bin : "00000000".substring(len - 8) + bin;
    }
    

    (Warning: untested ...)