十六进制、字符串互转

来源:互联网 发布:上门保养 知乎 编辑:程序博客网 时间:2024/06/08 03:35
此方法在原方法上进行了修改适合c#,
/** 方法一 */
    /**
     * 16进制字符串值转byte[]
     
     * @param src
     * @return
     */
    public static byte[] hexStr2Bytes(String src) {
        if (src == null || src.length() == 0)
            return null;
        int m = 0, n = 0;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = Convert.ToByte("0x"+str.Substring(i * 2, 2),16);
        }
        return ret;
    }
 
//以下方法没做测试,只使用了上边的方法,是好用的

    /**
     * byte[] 转16进制字符串
     
     * @param b
     * @return
     */
    public static String byteToHexStr(byte[] b) {
        if (b == null)
            return "";
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }
     

     
    /**
     * 方法二
     */ 
    public static String decodeEmpower0(ByteArrayInputStream in) throws IOException {
        byte[] bytes = IOUtils.toByteArray(in);
        List<String> list = new LinkedList<String>();
        for (int i = 0, len = bytes.length; i < len; i++) {
            String b = Integer.toHexString(bytes[i] & 0xFF);
            if (1 == b.length()) {
                list.add("0" + b);
            else {
                list.add(b);
            }
        }
        Collections.reverse(list);
        return StringUtils.join(list, "");
    }

原文地址:http://my.oschina.net/dexterman/blog/285374

0 0
原创粉丝点击