package util;
import java.util.ArrayList;
import java.util.List;
/**
* desc: 通用 基本类型数据转换方法
*/
public class CalcUtil {
private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* byte[]转换为:无符号int ok<br>
* 因为要返回无符号数,需要将返回值类型扩大到long
*
* @return 无符号的整数
*/
public static long byteArrayToUnsignedInt(byte[] b) {
int i = b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
return getUnsignedIntt(i);
}
/**
* int转byte数组 ok
*/
public static byte[] intToByteArray(int a) {
return new byte[]{
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}
/**
* short 转 byte数组 ok
*/
public static byte[] short2ByteArray(short a) {
return new byte[]{(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)};
}
/**
* 将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。 ok
*/
public static long getUnsignedIntt(int data) {
return (data & 0x0FFFFFFFFl);
}
/**
* byte数组转无符号short, ok
*
* @return 返回无符号short
*/
public static int byteArrayToUnsignedShort(byte[] b) {
short data = (short) (b[1] & 0xFF | (b[0] & 0xFF) << 8);
int i = data & 0x0FFFF;
return i;
}
/**
* Int,<br>
* 1 对于无符号 int,需要先将long转成int,再调用
* 2 对于有符号 int,直接调用
*/
public static List<Byte> addIntHL(List<Byte> list, int i) {
if (list == null) {
list = new ArrayList<Byte>();
}
byte[] byteArray = CalcUtil.intToByteArray(i);
list.add(byteArray[3]);
list.add(byteArray[2]);
list.add(byteArray[1]);
list.add(byteArray[0]);
return list;
}
/**
* Short,<br>
* 1 对于无符号 short,需要先将int转short,再调用
* 2 对于有符号 short,直接调用
*/
public static List<Byte> addShortHL(List<Byte> list, short s) {
if (list == null) {
list = new ArrayList<Byte>();
}
byte[] byteArray = CalcUtil.short2ByteArray(s);
list.add(byteArray[1]);
list.add(byteArray[0]);
return list;
}
/**
* byte[]
*/
public static List<Byte> addByteArray(List<Byte> list, byte[] byts) {
if (list == null) {
list = new ArrayList<Byte>();
}
for (byte b : byts) {
list.add(b);
}
return list;
}
/**
* byte[] to hex string
*/
public static String bytesToHexStr(byte[] bytes, char separator) {
char[] buf = new char[bytes.length * 2 + bytes.length - 1];
int index = 0;
for (byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
if (index <= buf.length - 3) {
buf[index++] = separator;
}
}
return new String(buf).trim();
}
}