Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีการแปลงสตริง hex เป็น byte Array ใน Java?


เราสามารถแปลงสตริงฐานสิบหกเป็นอาร์เรย์ไบต์ใน Java โดยการแปลงเลขฐานสิบหกเป็นค่าจำนวนเต็มก่อนโดยใช้วิธี parseInt() ของคลาส Integer ใน java สิ่งนี้จะส่งกลับค่าจำนวนเต็มซึ่งจะเป็นการแปลงทศนิยมของค่าฐานสิบหก จากนั้นเราจะใช้เมธอด toByteArray() ของคลาส BigInteger ซึ่งจะคืนค่าอาร์เรย์ไบต์

ตัวอย่าง

import java.math.BigInteger;
public class Demo {
   public static void main(String args[]) {
      String str = "1D08A";
      int it = Integer.parseInt(str, 16);
      System.out.println("Hexadecimal String " + str);
      BigInteger bigInt = BigInteger.valueOf(it);
      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