package cn.ec.common.tool;
import java.util.Arrays;
/**
* @author luckyman
* 字节转换
* 注意: 字节顺序都是小端
*/
public class ByteConvert {
/**
* 类型对应的字节长度
*/
private enum ByteLength {
/**
* short
*/
INT_16(2),
/**
* int
*/
INT_32(4),
/**
* long
*/
INT_64(8);
private int value;
ByteLength(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* bytes[offset++] = (byte) (param >> 8);
* bytes[offset++] = (byte) (param >> 16);
* bytes[offset++] = (byte) (param >> 24);
* bytes[offset++] = (byte) (param >> 32);
* bytes[offset++] = (byte) (param >> 40);
* bytes[offset++] = (byte) (param >> 48);
* bytes[offset++] = (byte) (param >> 56);
*
* @param bytes
* @param offset
* @param param
*/
public static void int64ToBytes(byte[] bytes, int offset, long param) {
for (int i = 0; i < ByteLength.INT_64.getValue(); i++) {
bytes[offset++] = (byte) (param >> (i * 8));
}
}
public static long bytesToInt64(byte[] bytes, int offset) {
long res = 0;
for (int i = 0; i < ByteLength.INT_64.getValue(); i++) {
res |= (long) (bytes[offset++] & 0xff) << (i * 8);
}
return res;
}
public static void int32ToBytes(byte[] bytes, int offset, int param) {
for (int i = 0; i < ByteLength.INT_32.getValue(); i++) {
bytes[offset++] = (byte) (param >> (i * 8));
}
}
/**
* 将float转换成字节
*
* @param bytes
* @param offset
* @param param
*/
public static void floatToBytes(byte[] bytes, int offset, float param) {
// 将float转换成int整型
ByteConvert.int32ToBytes(bytes, offset, Float.floatToIntBits(param));
}
/**
* int a = (bytes[0] & 0xff) << 0
* | (bytes[1] & 0xff) << 8
* | (bytes[2] & 0xff) << 16
* | (bytes[3] & 0xff) << 24;
*
* @param bytes
* @param offset
* @return
*/
public static int bytesToInt32(byte[] bytes, int offset) {
int res = 0;
for (int i = 0; i < ByteLength.INT_32.getValue(); i++) {
res |= (bytes[offset++] & 0xff) << (i * 8);
}
return res;
}
public static void int16ToBytes(byte[] bytes, int offset, short param) {
for (int i = 0; i < ByteLength.INT_16.getValue(); i++) {
bytes[offset++] = (byte) (param >> (i * 8));
}
}
public static short bytesToInt16(byte[] bytes, short offset) {
short res = 0;
for (int i = 0; i < ByteLength.INT_16.getValue(); i++) {
res |= (bytes[offset++] & 0xff) << (i * 8);
}
return res;
}
// public static void main(String[] args) {
// byte[] bytes = new byte[10];
// int32ToBytes(bytes, 0, 123456);
// System.out.println(Arrays.toString(bytes));
//
// System.out.println(bytesToInt32(bytes, 0));
// }
}
Java-基本类型与字节数组相互转换
最新推荐文章于 2021-02-21 04:09:28 发布