您的位置:首页 > 其它

字节数组 与 十六进制间的转换

2013-01-21 12:38 92 查看
/article/3770567.html

字节数组 与 十六进制间的转换

博客分类:
网络编程

bytebit数据类型操作符java

Java代码







package com.test;
import java.util.Arrays;
public class Bytes {

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")));

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