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,900 points
1,892 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,350 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, 2019 by Sirajul
• 59,170 points

Related Questions In Java

0 votes
2 answers
+15 votes
25 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, 2019 in Java by Suresh
• 720 points
233,371 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, 2019 in Java by Sirajul
• 59,170 points
388 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,900 points
749 views
0 votes
2 answers

Integer to String conversion in java

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

answered Jul 28, 2018 in Java by samarth295
• 2,220 points
433 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,900 points
583 views
0 votes
2 answers

How do I convert an input stream into a byte array

You could probably try this if you ...READ MORE

answered Aug 29, 2019 in Java by Sirajul
• 59,170 points
2,108 views
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,620 points
1,882 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, 2019 in Java by Sirajul
• 59,170 points
1,005 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,350 points
921 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP