I found the following way hex to binary conversion:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
While this approach works for small hex numbers, a hex number such as the following
A14AA1DBDB818F9759
Throws a NumberFormatException.
I therefore wrote the following method that seems to work:
private String hexToBin(String hex){ String bin = ""; String binFragment = ""; int iHex; hex = hex.trim(); hex = hex.replaceFirst("0x", ""); for(int i = 0; i < hex.length(); i++){ iHex = Integer.parseInt(""+hex.charAt(i),16); binFragment = Integer.toBinaryString(iHex); while(binFragment.length() < 4){ binFragment = "0" + binFragment; } bin += binFragment; } return bin; }
The above method basically takes each character in the Hex string and converts it to its binary equivalent pads it with zeros if necessary then joins it to the return value. Is this a proper way of performing a conversion? Or am I overlooking something that may cause my approach to fail?
Thanks in advance for any assistance.
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.
Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.
To convert a hexadecimal to a decimal manually, you must start by multiplying the hex number by 16. Then, you raise it to a power of 0 and increase that power by 1 each time according to the hexadecimal number equivalent.
BigInteger.toString(radix)
will do what you want. Just pass in a radix of 2.
static String hexToBin(String s) { return new BigInteger(s, 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