背景
今天改造.net的代码发现一个工具类在java中找不到对应的默认函数,索性自己写一个,验证可用。
public static byte[] toByteArray(int value) {
return new byte[] {
(byte) ((value >> 24) & 0xFF),
(byte) ((value >> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) (value & 0xFF)
};
}
public static byte[] toByteArray(int[] values) {
byte[] bytes = new byte[values.length * 4];
for (int i = 0; i < values.length; i++) {
int value = values[i];
bytes[i * 4] = (byte) ((value >> 24) & 0xFF);
bytes[i * 4 + 1] = (byte) ((value >> 16) & 0xFF);
bytes[i * 4 + 2] = (byte) ((value >> 8) & 0xFF);
bytes[i * 4 + 3] = (byte) (value & 0xFF);
}
return bytes;
}
public static int toInt(byte[] bytes) {
return (bytes[0] & 0xFF) << 24 |
(bytes[1] & 0xFF) << 16 |
(bytes[2] & 0xFF) << 8 |
(bytes[3] & 0xFF);
}