Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Convert Hex String to byte Array in Java
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.
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(str.substring(index, index + 2), 16);
val[i] = (byte) j;
}
Let us see the complete example.
Example
public class Demo {
public static void main(String args[]) {
String str = "p";
byte[] val = new byte[str.length() / 2];
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(str.substring(index, index + 2), 16);
val[i] = (byte) j;
}
System.out.println(val);
}
}
Output
[B@2a139a55
Advertisements
