java byte to hex

3145 ワード

String str;
byte[] bs = null;
bs =str.getBytes();
bs =str.getBytes("utf-8")
 
 
java  byte to hex 16
package com.longtop.client.codec.encryp;

public class HexTransfer {
    /**
     *  byte       16       ,  :byte[]{8,18}   :0813,  public static byte[]
     * hexStr2ByteArr(String strIn)          
     * 
     * @param arrB
     *                 byte  
     * @return        
     * @throws Exception
     *                       ,        
     */
    public static String byteArr2HexStr(byte[] arrB) {
        int iLen = arrB.length;
        //   byte         ,                
        StringBuffer sb = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            //         
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            //   0F        0
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

    /**
     *    16          byte  ,  public static String byteArr2HexStr(byte[] arrB)
     *          
     * 
     * @param strIn
     *                    
     * @return     byte  
     * @throws Exception
     *                       ,        
     * @author <a href="mailto:[email protected]">LiGuoQing</a>
     */
    public static byte[] hexStr2ByteArr(String strIn) {
        byte[] arrB = strIn.getBytes();
        int iLen = arrB.length;

        //           ,                2
        byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

}