Breaking News
Home / Java / Java Snippets / How to convert Hex String to Bytes and viceversa in Java?

How to convert Hex String to Bytes and viceversa in Java?

Java convert hex to byteConverting from hex String from a byte array and vice-versa is not available a function as part of JDK. The following shows a implementation of such methods. For Hex to Byte Array , it loops through the String chars in pair and coverts them to byte representation. Likewise for Byte Array to Hex, it loop through the bytes and for each one converts them to a Hex representation.  

Code

// Convert Hex String to Byte Array

public byte[] hex2Byte(String str)
    {
       byte[] bytes = new byte[str.length() / 2];
       for (int i = 0; i < bytes.length; i++)
       {
          bytes[i] = (byte) Integer
                .parseInt(str.substring(2 * i, 2 * i + 2), 16);
       }
       return bytes;
    }

// Convert Byte Arrary to Hex String
    public String byte2hex(byte[] b)
    {

     // String Buffer can be used instead

       String hs = “”;
       String stmp = “”;

       for (int n = 0; n < b.length; n++)
       {
          stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));

          if (stmp.length() == 1)
          {
             hs = hs + “0” + stmp;
          }
          else
          {
             hs = hs + stmp;
          }

          if (n < b.length – 1)
          {
             hs = hs + “”;
          }
       }

       return hs;
    }

[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 …

Advertisment ad adsense adlogger