Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to convert hex to bytes and viceversa in Java?

$
0
0
  1.     // hex to byte[]
  2.     publicbyte[] hex2Byte(String str)
  3.     {
  4.        byte[] bytes =newbyte[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.     publicString 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.     }

Viewing all articles
Browse latest Browse all 178

Trending Articles