How can I convert byte array into hex string in Java?

0 votes
I have a byte array. I want to convert it into hex strings. How to perform this conversion?
May 24, 2018 in Java by Sushmita
• 6,880 points
385 views

2 answers to this question.

0 votes
private final static char[] hexarr = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexchars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexchars[j * 2] = hexarr[v >>> 4];
        hexchars[j * 2 + 1] = hexarr[v & 0x0F];
    }
    return new String(hexchars);
}
answered May 24, 2018 by sharth
• 3,320 points
0 votes
public static String byteArrayToHex(byte[] a) {
   StringBuilder sb = new StringBuilder(a.length * 2);
   for(byte b: a)
      sb.append(String.format("%02x", b));
   return sb.toString();
}
answered Aug 29 by Sirajul
• 25,420 points

Related Questions In Java

0 votes
2 answers
+14 votes
18 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7 in Java by Suresh
• 700 points
77,630 views
0 votes
2 answers

How to convert a java string into byte array

Try using String.getBytes(). It returns a byte[] ...READ MORE

answered Aug 22 in Java by Sirajul
• 25,420 points
53 views
0 votes
3 answers

How can I add new elements to an Array in Java

String[] source = new String[] { "a", ...READ MORE

answered Sep 19, 2018 in Java by Sushmita
• 6,880 points
112 views
0 votes
2 answers

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE

answered Jul 27, 2018 in Java by samarth295
• 2,190 points
71 views
0 votes
3 answers

String to Double conversion in java

Double temp = Double.valueOf(str); number = temp.doubleValue(); READ MORE

answered Sep 10, 2018 in Java by Sushmita
• 6,880 points
46 views
0 votes
2 answers
0 votes
1 answer

Formatting Double Value in Java

An alternative is to use String.format: double[] arr = ...READ MORE

answered May 15, 2018 in Java by Rishabh
• 3,540 points
57 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20 in Java by Sirajul
• 25,420 points
132 views
0 votes
1 answer

How to convert a string representation of a hex dump to a byte array using Java?

public static byte[] hexStringToByteArray(String s) { ...READ MORE

answered Sep 26, 2018 in Java by sharth
• 3,320 points
152 views