Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex string to binary string

Tags:

java

string

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?

like image 698
user871695 Avatar asked Dec 27 '11 03:12

user871695


People also ask

Can you convert hex 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.

How do you convert a number to a binary string?

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.

How do you convert hex to bytes?

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];


2 Answers

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;
}
like image 85
Sergey Kalinichenko Avatar answered Oct 17 '22 07:10

Sergey Kalinichenko


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);
}
like image 33
Sean Patrick Floyd Avatar answered Oct 17 '22 05:10

Sean Patrick Floyd