- int 转为byte[]
/**
* 整型转byte数组
*
* @param i
* @param isBig true:大端模式 false:小端模式
* @return 数组
*/
public static byte[] intToByteArray(int i, boolean isBig) {
byte[] result = new byte[4];
// 由高位到低位
if (isBig) {
result[0] = (byte) ((i >> 24) & 0xFF);
result[1] = (byte) ((i >> 16) & 0xFF);
result[2] = (byte) ((i >> 8) & 0xFF);
result[3] = (byte) (i & 0xFF);
} else {
result[3] = (byte) ((i >> 24) & 0xFF);
result[2] = (byte) ((i >> 16) & 0xFF);
result[1] = (byte) ((i >> 8) & 0xFF);
result[0] = (byte) (i & 0xFF);
}
return result;
}
- byte[]转为int
/**
* byte数组转整型
*
* @param bytes byte数组
* @param start 起始位
* @param isBig true:大端模式 false:小端模式
* @return 整数
*/
public static int byteArrayToInt(byte[] bytes, int start, boolean isBig) {
int value = 0;
if (isBig) {
value += (bytes[start] & 0x000000FF) << 24;
value += (bytes[start + 1] & 0x000000FF) << 16;
value += (bytes[start + 2] & 0x000000FF) << 8;
value += (bytes[start + 3] & 0x000000FF);
} else {
value += (bytes[start] & 0x000000FF);
value += (bytes[start + 1] & 0x000000FF) << 8;
value += (bytes[start + 2] & 0x000000FF) << 16;
value += (bytes[start + 3] & 0x000000FF) << 24;
}
return value;
}
- short转为byte[]
/**
* short 转为 byte数组
*
* @param i short
* @param isBig true:大端模式 false:小端模式
* @return
*/
public static byte[] shortToByteArray(short i, boolean isBig) {
byte[] result = new byte[2];
// 由高位到低位
if (isBig) {
result[0] = (byte) ((i >> 8) & 0xFF);
result[1] = (byte) (i & 0xFF);
} else {
result[0] = (byte) (i & 0xFF);
result[1] = (byte) ((i >> 8) & 0xFF);
}
return result;
}
- byte[]转为short
/**
* bytes数组转为 short
*
* @param bytes 数组
* @param start 起始位
* @param isBig true:大端模式 false:小端模式
* @return 短整型
*/
public static short byteArrayToShort(byte[] bytes, int start, boolean isBig) {
short value = 0;
if (isBig) {
value += (bytes[start] & 0x000000FF) << 8;
value += (bytes[start + 1] & 0x000000FF);
} else {
value += (bytes[start] & 0x000000FF);
value += (bytes[start + 1] & 0x000000FF) << 8;
}
return value;
}
- byte转为16进制字符串
/**
* 字节 转 16进制
*
* @param bt 字节
* @return Hex 十六进制字符串
*/
public static String byte2Hex(byte bt) {
String[] strHex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
String resStr = "";
int low = (bt & 15);
int high = bt >> 4 & 15;
resStr = strHex[high] + strHex[low];
return resStr;
}
- byte[]转为16进制字符串
/**
* 字节数组转为 16进制字符串
*
* @param data 字节数组
* @param length 指定长度,若小于等于0,则转换整个字节数组
* @return
*/
public static String bytes2Hex(byte[] data, int length) {
if (data == null) return "";
if (length <= 0) length = data.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(byte2Hex(data[i]) + " ");
}
return sb.toString();
}
说明:该转换常用于java自定义用户层通讯协议。