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;
}
replace()must be called on the result ofString.format()not on thebinrayString.