java中String\十六进制String\byte[]之间相互转换函数

来源:互联网 发布:dd命令 备份linux系统 编辑:程序博客网 时间:2024/06/05 07:29

 转自 http://hi.baidu.com/jingzhang_2007/blog/item/df1d4317df07430cc93d6dbe.html


从网上找到了如下转换的例子,发现其实是有点问题的。问题在将hex的string转换成byte[]的时候,大于10的部分会有问题,比如“000102030405060708090a0b0c0d0e” 转换成了“0123456789-1-1-1-1-1-1”..

public static String stringToHexString(String strPart) {        String hexString = "";        for (int i = 0; i < strPart.length(); i++) {            int ch = (int) strPart.charAt(i);            String strHex = Integer.toHexString(ch);             hexString = hexString + strHex;        }        return hexString;    }private static String hexString="0123456789ABCDEF";/** 将字符串编码成16进制数字,适用于所有字符(包括中文)*/public static String encode(String str){// 根据默认编码获取字节数组byte[] bytes=str.getBytes();StringBuilder sb=new StringBuilder(bytes.length*2);// 将字节数组中每个字节拆解成2位16进制整数for(int i=0;i<bytes.length;i++){sb.append(hexString.charAt((bytes[i]&0xf0)>>4));sb.append(hexString.charAt((bytes[i]&0x0f)>>0));}return sb.toString();}/** 将16进制数字解码成字符串,适用于所有字符(包括中文)*/public static String decode(String bytes){ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);// 将每2位16进制整数组装成一个字节for(int i=0;i<bytes.length();i+=2)baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));return new String(baos.toByteArray());}

但是这部分是没有问题的。

private static byte uniteBytes(byte src0, byte src1) {     byte _b0 = Byte.decode("0x" + new String(new byte[] {src0})).byteValue();     _b0 = (byte) (_b0 << 4);     byte _b1 = Byte.decode("0x" + new String(new byte[] {src1})).byteValue();     byte ret = (byte) (_b0 | _b1);     return ret;public static byte[] HexString2Bytes(String src){   byte[] ret = new byte[6];    byte[] tmp = src.getBytes();    for(int i=0; i<6; ++i )   {     ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);       }   return ret;}


原创粉丝点击