# 如何在 Java 中以十六進位制字串轉換位元組陣列

## `HEX_ARRAY[]` 方法將位元組陣列轉換為 Java 中的十六進位制字串

``````public class SimpleTesting {
public static void main(String[] args) {
char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
byte b[] = new byte[2];
b[0] = 20;
b[1] = 10;
char[] hexChars = new char[b.length * 2];
for (int j = 0; j < b.length; j++) {
int v = b[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
System.out.println(hexChars);
}
}
``````

``````140A
``````

## `Hex.encodeHexString()` 方法將 Java 中的位元組陣列轉換為十六進位制字串

``````import java.util.Arrays;
import org.apache.commons.codec.binary.Hex;

public class SimpleTesting {
public static void main(String[] args) {
byte[] byteArray = new byte[] {'S', 'i', 'm', 'p', 'l', 'e', 'T', 'e', 's', 't', 'i', 'n', 'g'};
System.out.println("Byte Array: ");
System.out.println(Arrays.toString(byteArray));
System.out.println("Hex String Conversion: " + Hex.encodeHexString(byteArray));
}
}
``````

``````Byte Array:
[83, 105, 109, 112, 108, 101, 84, 101, 115, 116, 105, 110, 103]
Hex String Conversion: 53696d706c6554657374696e67
``````

## `DatatypeConverter()` 方法以 Java 中的十六進位制字串轉換位元組陣列

``````import java.util.Arrays;
import javax.xml.bind.*;

public class SimpleTesting {
public static void main(String[] args) {
byte byteArray[] = {(byte) 00, (byte) 10, (byte) 20, (byte) 30, (byte) 40};
String hexString = javax.xml.bind.DatatypeConverter.printHexBinary(byteArray);
System.out.println("Byte Array: ");
System.out.println(Arrays.toString(byteArray));
System.out.println("Hex String Conversion: " + hexString);
}
}
``````

``````Byte Array:
[0, 10, 20, 30, 40]
Hex String Conversion: 000A141E28
``````

## 用 `append(.format)` 方法將 Java 中的位元組陣列轉換為十六進位制字串

``````public class SimpleTesting {
public static void main(String[] args) {
byte a[] = new byte[2];
a[0] = 20;
a[1] = 10;
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a) sb.append(String.format("%02x", b));
System.out.println(sb);
}
}
``````

``````140a
``````