Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex-encoded String to Byte Array

String str = "9B7D2C34A366BF890C730641E6CECF6F"; 

I want to convert str into byte array, but str.getBytes() returns 32 bytes instead of 16.

like image 240
Qaiser Mehmood Avatar asked Jul 11 '11 13:07

Qaiser Mehmood


People also ask

How can I convert a hex string to a byte array?

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]; Now, take a for loop until the length of the byte array.

Is hex a 1 byte?

Now, let's convert a hexadecimal digit to byte. As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.

How many hex is 4 bytes?

Hexadecimal is used in the transfer encoding Base16, in which each byte of the plaintext is broken into two 4-bit values and represented by two hexadecimal digits.

Can we convert string to byte?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.


2 Answers

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.

The apache commons-codec has a class for that, Hex.

String s = "9B7D2C34A366BF890C730641E6CECF6F";     byte[] bytes = Hex.decodeHex(s.toCharArray()); 
like image 81
pap Avatar answered Sep 19 '22 20:09

pap


Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

String str = "9B7D2C34A366BF890C730641E6CECF6F"; byte[] bytes = DatatypeConverter.parseHexBinary(str); 

The class also provides type conversions for many other formats that are generally used in XML.

like image 43
Archimedes Trajano Avatar answered Sep 23 '22 20:09

Archimedes Trajano