Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hex code in the form of: 3a5f771c

1 Answer

0 votes
by (46k points)

Check out this example:

Input:

public class ByteHex {

    public static void main(String[] args) {

        byte[] bytes = {10, 2, 15, 11};

        for; (byte b : bytes) {

            String st = String.format("%02X", b);

            System.out.print(st);

        }

    }

}

Output:

0A020F0B

In this program, we have a byte array named bytes. To convert byte array to a hex value, we loop over each byte in the array and use String's format().

 %02X is used to print two places (02) of Hexadecimal (X) value and store it in the string st.

I hope this will help you, Happy Learning...!!

Browse Categories

...