I would like to convert a hex string to a binary string. For example, Hex 2 is 0010. Below is the code:
String HexToBinary(String Hex)
{
int i = Integer.parseInt(Hex);
String Bin = Integer.toBinaryString(i);
return Bin;
}
However this only works for Hex 0 - 9; it won't work for Hex A - F because it uses int
. Can anyone enhance it?
Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.
toBinaryString(int i) To convert an integer to binary, we can simply call the public static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];
You need to tell Java that the int is in hex, like this:
String hexToBinary(String hex) {
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
return bin;
}
the accepted version will only work for 32 bit numbers.
Here's a version that works for arbitrarily long hex strings:
public static String hexToBinary(String hex) {
return new BigInteger(hex, 16).toString(2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With