Algorithm


  1. Input: Accept a byte array as input.

  2. Initialize an empty string to store the hexadecimal representation.

  3. Iterate through each byte in the array.

    • For each byte, extract the two nibbles (4 bits each).
    • Convert each nibble to its hexadecimal equivalent (0-9, A-F).
  4. Append the hexadecimal representation of each nibble to the string.

  5. Continue iterating until all bytes have been processed.

  6. The resulting string is the hexadecimal representation of the byte array.

 

Code Examples

#1 Code Example- Convert Byte Array to Hex value

Code - Java Programming

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);
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
0A020F0B

#2 Code Example- Convert Byte Array to Hex value using byte operations

Code - Java Programming

public class ByteHex {

    private final static char[] hexArray = "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] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static void main(String[] args) {

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

        String s = bytesToHex(bytes);
        System.out.println(s);

    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
0A020F0B
Advertisements

Demonstration


Java Programing Example to Convert Byte Array to Hexadecimal-DevsEnv