- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Convert byte Array to Hex String in Java
- How to convert hex string to byte Array in Java?
- How to convert a byte array to hex string in Java?
- How to convert a byte array to a hex string in Java?
- Java Program to convert byte[] array to String
- Java Program to convert String to byte array
- Convert byte to String in Java
- Convert Integer to Hex String in Java
- Java Program to convert byte to string
- Java Program to convert string to byte
- How to convert byte array to string in C#?
- How to convert BLOB to Byte Array in java?
- How to convert Byte Array to Image in java?
- How to convert Image to Byte Array in java?
- How to convert InputStream to byte array in Java?

Advertisements