您的位置:首页 > 编程语言 > Java开发

java byte型数组和16进制字符串互相转化方法

2010-06-30 17:06 477 查看
public static String printHexString( byte[] b) {

String result="";

for (int i = 0; i < b.length; i++) {

String hex = Integer.toHexString(b[i] & 0xFF);

if (hex.length() == 1) {

hex = '0' + hex;

}

result=result+hex.toUpperCase();

}

return result;

}

public static byte[] hexStringToBytes(String hexString) {

if (hexString == null || hexString.equals("")) {

return null;

}

hexString = hexString.toUpperCase();

int length = hexString.length() / 2;

char[] hexChars = hexString.toCharArray();

byte[] d = new byte[length];

for (int i = 0; i < length; i++) {

int pos = i * 2;

d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

}

return d;

}

private static byte charToByte(char c) {

return (byte) "0123456789ABCDEF".indexOf(c);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: