Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hexadecimal string (hex) to a binary string

Tags:

java

hex

binary

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.

like image 412
Mark Avatar asked Feb 12 '12 04:02

Mark


People also ask

How do you convert from hexadecimal to binary?

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.

Can hex convert to binary directly?

Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.

How do you convert hex to base10?

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.


1 Answers

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); } 
like image 145
Mike Samuel Avatar answered Oct 19 '22 14:10

Mike Samuel