1,十六进制转ASCII码
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
2,时间格式转换
public static String stampToDate(long s) {
String ss;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(s);
ss = simpleDateFormat.format(date);
return ss;
}
3,一个长数组上截取某一部分
public static byte[] getbytes(int begin_index, int length, byte[] bs) {
byte[] b = new byte[length];
for (int i = begin_index; i < length + begin_index; i++) {
b[i - begin_index] = bs[i];
}
return b;
}
4,byte->long(byte是8个长度)
public static long byteArrayToLong(byte[] bb) {
return ((((long) bb[0] & 0xff) << 56) | (((long) bb[1] & 0xff) << 48)
| (((long) bb[2] & 0xff) << 40) | (((long) bb[3] & 0xff) << 32)
| (((long) bb[4] & 0xff) << 24) | (((long) bb[5] & 0xff) << 16)
| (((long) bb[6] & 0xff) << 8) | (((long) bb[7] & 0xff) << 0));
}
5,byte->int
public static int byteArrayToInt(byte[] b, int num) {
if (num == 4) {
return b[3] & 0xFF << 0 | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
} else if (num == 3) {
return b[2] & 0xFF << 0 | (b[1] & 0xFF) << 8 | (b[0] & 0xFF) << 16;
} else if (num == 2) {
return b[1] & 0xFF << 0 | (b[0] & 0xFF) << 8;
} else {
return b[0] & 0xFF;
}
}
6,int转byte数组
public static byte[] intToByteArray(int a, int num) {
if (num == 4) {
return new byte[] { (byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF) };
} else if (num == 3) {
return new byte[] { (byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
} else {
return new byte[] { (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
}
}