0

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

vandermies
  • 183
  • 3
  • 14
  • *"is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)?"* no, but `String.format()` can fill missing chars before another string... – Timothy Truckle Nov 06 '16 at 11:27

3 Answers3

2

My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)?

No, there isn't. You have to write it yourself.

Here's one simple way. If you know the input is always a single byte, then you could add 256 to the number before calling toBinaryString. That way, the string will be guaranteed to be 9 characters long, and then you can just shave off the first character using substring:

String bin = Integer.toBinaryString(256 + i).substring(1);
janos
  • 120,954
  • 29
  • 226
  • 236
0

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 ...)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I've concatenated this way. Thanks!

private String hexToBin (String hex){
        int i = Integer.parseInt(hex, 16);
        String bin = Integer.toBinaryString(i);
        while (bin.length()<8){
            bin="0"+bin;
        }
        return bin;

    }
vandermies
  • 183
  • 3
  • 14