Breaking News
Home / Java / Java Snippets / How to convert hex to bytes and viceversa in Java?

How to convert hex to bytes and viceversa in Java?

  1.     // hex to byte[]
  2.     public byte[] hex2Byte(String str)
  3.     {
  4.        byte[] bytes = new byte[str.length() / 2];
  5.        for (int i = 0; i < bytes.length; i++)
  6.        {
  7.           bytes[i] = (byte) Integer
  8.                 .parseInt(str.substring(2 * i, 2 * i + 2), 16);
  9.        }
  10.        return bytes;
  11.     }
  12.    
  13.    // bytes to hex
  14.     public String byte2hex(byte[] b)
  15.     {
  16.        String hs = "";
  17.        String stmp = "";
  18.  
  19.        for (int n = 0; n < b.length; n++)
  20.        {
  21.           stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
  22.  
  23.           if (stmp.length() == 1)
  24.           {
  25.              hs = hs + "0" + stmp;
  26.           }
  27.           else
  28.           {
  29.              hs = hs + stmp;
  30.           }
  31.  
  32.           if (n < b.length 1)
  33.           {
  34.              hs = hs + "";
  35.           }
  36.        }
  37.  
  38.        return hs;
  39.     }
[pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply