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,920 points
2,968 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,370 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,230 points

Related Questions In Java

0 votes
2 answers
+17 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
253,813 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,230 points
1,495 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,920 points
13,322 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
1,236 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,920 points
1,752 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,230 points
3,889 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
2,517 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,230 points
2,358 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,370 points
2,182 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP