將 16 進位制字串轉換成位元組陣列


要將 16 進位制字串轉換成位元組陣列,你需要先獲取給定字串的長度,並在建立一個新的位元組陣列時包含它。

byte[] val = new byte[str.length() / 2];

現在,建立一個直到位元組陣列的長度的 for 迴圈。

for (int i = 0; i < val.length; i++) {
   int index = i * 2;
   int j = Integer.parseInt(str.substring(index, index + 2), 16);
   val[i] = (byte) j;
}

讓我們看一個完整的示例。

示例

 線上演示

public class Demo {
   public static void main(String args[]) {
      String str = "p";
      byte[] val = new byte[str.length() / 2];
      for (int i = 0; i < val.length; i++) {
         int index = i * 2;
         int j = Integer.parseInt(str.substring(index, index + 2), 16);
         val[i] = (byte) j;
      }
      System.out.println(val);
   }
}

輸出

[B@2a139a55

更新於: 2020-06-26

12K+ 次瀏覽

開啟你的職業生涯

完成課程獲得透過認證

開始
廣告
© . All rights reserved.