ใน Java สามารถแปลงสตริง Hexadecimal เป็น Byte Array ได้โดยการแปลงค่า Hexadecimal ให้เป็นค่าจำนวนเต็ม (Integer) ก่อน โดยใช้เมธอด parseInt() ของคลาส Integer โดยระบุฐานเลข (radix) เป็น 16 ซึ่งจะคืนค่าจำนวนเต็มที่เป็นการแปลงค่าทศนิยมของค่า Hexadecimal จากนั้นจึงใช้เมธอด toByteArray() ของคลาส BigInteger เพื่อแปลงค่าจำนวนเต็มนั้นให้เป็น Byte Array
ตัวอย่างโค้ด
import java.math.BigInteger;
public class HexToByteArray {
public static void main(String[] args) {
String hexString = "1D08A";
int decimalValue = Integer.parseInt(hexString, 16);
System.out.println("Hexadecimal String: " + hexString);
BigInteger bigInt = BigInteger.valueOf(decimalValue);
byte[] byteArray = bigInt.toByteArray();
System.out.print("Byte Array: ");
for (int i = 0; i < byteArray.length; i++) {
System.out.print(byteArray[i] + "\t");
}
}
}
ผลลัพธ์
Hexadecimal String: 1D08A
Byte Array: 1 -48 -118
คำอธิบายเพิ่มเติม
วิธีนี้เหมาะสำหรับการแปลงค่า Hexadecimal ขนาดเล็ก แต่สำหรับค่าที่ใหญ่กว่าค่าสูงสุดของ Integer (2,147,483,647) ควรใช้ BigInteger โดยตรงในการแปลงจากสตริง Hexadecimal เพื่อป้องกันการล้น (overflow) ดังนี้:
BigInteger bigInt = new BigInteger(hexString, 16);
byte[] byteArray = bigInt.toByteArray();