首页 > 编程语言 > 详细

十六进制的字符串和字节数组之间的转换

时间:2015-03-27 19:47:25      阅读:272      评论:0      收藏:0      [点我收藏+]
**
 * This class provides convenient functions to convert hex string to byte array and vice versa.*
 */
public class HexUtil {
     
    private static final String HEX_CHARS = "0123456789abcdef";

    private HexUtil() {}
        
    /**
     * Converts a byte array to hex string.
     * 
     * @param b -
     *            the input byte array
     * @return hex string representation of b.
     */

    public static String toHexString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(HexUtil.HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
            sb.append(HexUtil.HEX_CHARS.charAt(b[i] & 0x0F));
        }
        return sb.toString();
    }

    /**
     * Converts a hex string into a byte array.
     * @param s -
     *            string to be converted
     * @return byte array converted from s
     */
    public static byte[] toByteArray(String s) {
        byte[] buf = new byte[s.length() / 2];
        int j = 0;
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) ((Character.digit(s.charAt(j++), 16) << 4) | Character.digit(s.charAt(j++), 16));
        }
        return buf;
    }


   
}

 

十六进制的字符串和字节数组之间的转换

原文:http://www.cnblogs.com/shi-blog/p/4372410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!