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

Convert byte array to hexadecimal string in Java

Texte principal

public static void main(String args[]) {

Voici notre tableau de bytes.

public static String display(byte[] b1) {
   StringBuilder strBuilder = new StringBuilder();
   for(byte val : b1) {
      strBuilder.append(String.format("%02x", val&0xff));
   }
   return strBuilder.toString();
}

Nous avons créé ici une méthode personnalisée "display" et avons passé la valeur de tableau de bytes. La même méthode convertit le tableau de bytes en chaîne hexadécimale.

Maintenant, regardons l'exemple dans son ensemble.

Exemple
   public class Demo {
      public static void main(String args[]) {
      /* byte[] b = new byte[]{'p', 'q', 'r'};-caractères imprimables
      caractères, par exemple 0 est NUL, 5 est ENQ au format ASCII */
      String str = new String(b);
      System.out.println(str);
      //Tableau de bytes de chaîne hexadécimale
      System.out.println("ByteArrayToHexString=" + display(b));
   }
   public static String display(byte[] b1) {
      StringBuilder strBuilder = new StringBuilder();
      for(byte val : b1) {
         strBuilder.append(String.format("%02x", val&0xff));
      }
      return strBuilder.toString();
   }
}

Résultat de la sortie

pqr
ByteArrayToHexString= 707172