English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Convertir une chaîne hexadécimale en tableau d'octets en Java

Pour convertir une chaîne hexadécimale en tableau de bytes, vous devez d'abord obtenir la longueur de la chaîne donnée et l'inclure lors de la création du nouveau tableau de bytes.

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

Maintenant, exécutons une boucle for jusqu'à la longueur de l'array de bytes.

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

Voyons un exemple complet.

Exemple

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;++) {
         int index = i * 2;
         int j = Integer.parseInt(str.substring(index, index + 2), 16);
         val[i] = (byte) j;
      }
      System.out.println(val);
   }
}

Résultat de la sortie

[B@2a139a55