How to convert a byte array to a hexadecimal string in Java?
Hello everyone! I'm new to Java and I've encountered a task: I need to convert a byte array (byte[]) into a string representing the hexadecimal (hex) representation of these bytes. For example, if I have a byte array byte[] {0x0A, 0xFF, 0x1B}, I want to get the string "0AFF1B".
The problem is that when I try to simply create a string from the byte array using new String(bytes), I get gibberish instead of a hex representation. I understand that this is incorrect because String expects characters in an encoding, not arbitrary bytes.
I wrote a simple code that tries to do this manually:
```java
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(Integer.toHexString(b & 0xFF));
}
return s
```
No answers yet.
Log in to leave an answer
Blogs