Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert byte array to hexString in java? [duplicate]

Tags:

java

I have byte array that consist of hex values like CA ,FA,21,33

But I want to list them in JList as a single element CAFA2133. In order to list them in JList I think I need to convert it to string. So any recommendation?

like image 695
hiii Avatar asked Mar 15 '13 09:03

hiii


People also ask

Can we convert byte to double in Java?

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

How does Java convert byte array to string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you convert bytes to long objects?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();


2 Answers

public static String bytesToHex(byte[] in) {     final StringBuilder builder = new StringBuilder();     for(byte b : in) {         builder.append(String.format("%02x", b));     }     return builder.toString(); } 
like image 112
Vasyl Keretsman Avatar answered Oct 01 '22 14:10

Vasyl Keretsman


You need to look at String.format() and the Formatter specifications.

e.g.

String.format("%02x", byteValue);

Iterate through the array and append each String.format() result to a StringBuilder

like image 31
Brian Agnew Avatar answered Oct 01 '22 16:10

Brian Agnew