阅读:17556次   评论:3条   更新时间:2012-10-18    
private final static byte[] hex = "0123456789ABCDEF".getBytes();

private static int parse(char c) {
	if (c >= 'a')
		return (c - 'a' + 10) & 0x0f;
	if (c >= 'A')
		return (c - 'A' + 10) & 0x0f;
	return (c - '0') & 0x0f;
}
// 从字节数组到十六进制字符串转换
public static String Bytes2HexString(byte[] b) {
	byte[] buff = new byte[2 * b.length];
	for (int i = 0; i < b.length; i++) {
		buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
		buff[2 * i + 1] = hex[b[i] & 0x0f];
	}
	return new String(buff);
}

// 从十六进制字符串到字节数组转换
public static byte[] HexString2Bytes(String hexstr) {
	byte[] b = new byte[hexstr.length() / 2];
	int j = 0;
	for (int i = 0; i < b.length; i++) {
		char c0 = hexstr.charAt(j++);
		char c1 = hexstr.charAt(j++);
		b[i] = (byte) ((parse(c0) << 4) | parse(c1));
	}
	return b;
}

public static void main(String[] args) {
	byte[] bt = new byte[]{10, 2, 12, 14, 1, 0, 0, 1, 0, 31, 45, 1, 8, 0, 1, 0, -96, -45, 10, 3};
	System.out.println(Bytes2HexString(bt));
	System.out.println(Arrays.toString(HexString2Bytes("0A020C0E01000001001F2D0108000100A0D30A03")));
}


打印

0A020C0E01000001001F2D0108000100A0D30A03
[10, 2, 12, 14, 1, 0, 0, 1, 0, 31, 45, 1, 8, 0, 1, 0, -96, -45, 10, 3]
评论 共 3 条 请登录后发表评论
3 楼 cuisuqiang 2013-07-19 14:18
// 返回无符号的2进制表示 1110011
String hex = Integer.toBinaryString(115);
System.out.println(hex);
// 返回2进制的字符串1110011对应的值 115
System.out.println(Integer.valueOf("1110011", 2));

// 16进制值转换成二进制
System.out.println(Long.parseLong("49", 16));
System.out.println(Long.parseLong("2F", 16));
2 楼 sgq0085 2013-04-08 13:00
为什么 buff[2 * i] = hex[(b[i] >> 4) & 0x0f]; 
这里 & 0x0f  是做什么用的?
1 楼 befairy 2013-02-27 14:26
小手一抖,经验到手!

谢谢LZ分享。。

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics