lifeisaloop
lifeisaloop

Reputation: 83

Convert Hex String to Binary String - Java

Ok so i want to convert a Hex string to a Binary String so that i can do some bit swaps and subs etc down the line and i come across what i thought was the answer on here Convert hex string to binary string but this caused me some problems.

String hexToBinary(String hexadecimalString) {
    int i = Integer.parseInt(hexadecimalString, 16);
    String binaryString = Integer.toBinaryString(i);
    return binaryString;
}

However, for example if i passed in the hexadecimal string "03" it would only return a binary string of "11". Or if i were to pass in the hex string "41" it would return a binary string of "1000001". How can I make it so that it will always return a binary string of length 8 bits? All help greatly appreciated in advance :)

Tried your suggestion of padding the binary string but it didn't work, this is what i tried, can you see what I've done wrong?

String hexToBinary(String hexString) {
    int i = Integer.parseInt(hexString, 16);
    String binaryString = Integer.toBinaryString(i);
    String padded = String.format("%8s", binaryString.replace(' ', '0'));
    return padded;
}

Upvotes: 1

Views: 6199

Answers (3)

Kumar
Kumar

Reputation: 325

String hexToBinary(String hexadecimalString) {
int i = Integer.parseInt(hexadecimalString, 16);
String binaryString = Integer.toBinaryString(i);
while (binaryString .length() < 8) {
        binaryString  = "0" + binaryString ;
    }
return binaryString;
}

adding 0 at start of string till length of binaryString is 8

Upvotes: 1

SubOptimal
SubOptimal

Reputation: 22993

Out of many other solutions this could be one.

StringBuilder sb = new StringBuilder();
String binaryString = Integer.toBinaryString(41);
for (int i = binaryString.length(); i < 8; i++) {
    sb.append('0');
}
sb.append(binaryString);
System.out.println(sb.toString());

or this one

StringBuilder sb = new StringBuilder("00000000");
sb.append(Integer.toBinaryString(41));
System.out.println(sb.substring(sb.length()-8));

or even this one

String s = "00000000" + Integer.toBinaryString(41);
System.out.println(s.substring(s.length()-8));

Upvotes: 0

Iswanto San
Iswanto San

Reputation: 18569

Use String.format

Try this:

String.format("%8s", Integer.toBinaryString(i)).replace(' ', '0')

Upvotes: 1

Related Questions