Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hex strings to byte values in Java

Tags:

I have a String array. I want to convert it to byte array. I use the Java program. For example:

String str[] = {"aa", "55"}; 

convert to:

byte new[] = {(byte)0xaa, (byte)0x55}; 

What can I do?

like image 657
brian Avatar asked Dec 28 '11 06:12

brian


People also ask

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

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

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.


2 Answers

String str = "Your string";  byte[] array = str.getBytes(); 
like image 148
Lion Avatar answered Sep 22 '22 02:09

Lion


Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?

If yes, then for each string item I would do the following:

  1. check that a string consists only of 2 characters
  2. these chars are in '0'..'9' or 'a'..'f' interval (take their case into account as well)
  3. convert each character to a corresponding number, subtracting code value of '0' or 'a'
  4. build a byte value, where first char is higher bits and second char is lower ones. E.g.

    int byteVal = (firstCharNumber << 4) | secondCharNumber; 
like image 25
Wizart Avatar answered Sep 22 '22 02:09

Wizart