1、字节数组装换为十六进制字符串
private final static byte[] hex = "0123456789ABCDEF".getBytes();
/**
* 从字节数组到十六进制字符串转换
*/
public static String bytesToHexString(byte[] b, int bytesLen) {
byte[] buff = new byte[2 * bytesLen];
for (int i = 0; i < bytesLen; i++) {
buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
buff[2 * i + 1] = hex[b[i] & 0x0f];
}
return new String(buff);
}
2、十六进制字符串转换为字节数组
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 byte[] hexStringToBytes(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;
}
3、字节数组转换为整型(大端模式,高位在前)
/**
* byte数组转大端模式int(高位在前)
* @param bytes 字节数组
* @return 整型数字
*/
public static int bytesToBigInt(byte[] bytes) {
int tmp = 0;
tmp = bytes[0] & 0xFF;
tmp = (tmp << 8) | (bytes[1] & 0xff);
tmp = (tmp << 8) | (bytes[2] & 0xff);
tmp = (tmp << 8) | (bytes[3] & 0xff);
return tmp;
}
4、整型转换为字节数组(大端模式,高位在前)
/**
* int转byte数组(高位在前)
* @param i 整型数字
* @return 字节数组
*/
public static byte[] bigIntToBytes(int i) {
byte[] abyte = new byte[4];
abyte[0] = (byte) ((i >> 24) & 0xFF);
abyte[1] = (byte) ((i >> 16) & 0xFF);
abyte[2] = (byte) ((i >> 8) & 0xFF);
abyte[3] = (byte) (i & 0xFF);
return abyte;
}
5、字节数组转换为整型(小端模式,低位在前)
public static int byteToint(byte[] res) {
int targets = (res[0] & 0xFF);
targets = targets | ((res[1] << 8) & 0xFF00);
// 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000
targets = targets | ((res[2] << 24) >>> 8);
targets = targets | (res[3] << 24);
return targets;
}
6、整型转换为字节数组(小端模式,低位在前)
public static byte[] intTobyte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);
targets[1] = (byte) ((res >> 8) & 0xff);
targets[2] = (byte) ((res >> 16) & 0xff);
targets[3] = (byte) (res >>> 24);
return targets;
}
7、整型转为长整型(防止显示为负数)
/**
* 将int数据转换为0~4294967295,即0xFFFFFFFF
* @param data
* @return
*/
public static long getUnsignedInt(int data) {
return data& 0x0FFFFFFFFL;
}