Write a Java Program to Convert Byte Array to Hexadecimal

Java Program to Convert Byte Array to Hexadecimal

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Convert Byte Array to Hexadecimal
Java Program to Convert Byte Array to Hexadecimal

Write a Java Program to Convert Byte Array to Hexadecimal

PROGRAM: Java Program to Convert Byte Array to Hexadecimal

/* Java Program to Convert Byte Array to Hexadecimal */

1: Convert Byte Array to Hex value

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);
}
}
}

 2: Convert Byte Array to Hex value using byte operations

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);

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *