文章目录
- 方法1 自己写
- int转byte数组
- byte数组转int
- 参考:https://blog.csdn.net/qq_41054313/article/details/88424454
- 方法2 使用java NIO包的功能
- int转byte数组
- byte数组转int
- 参考:https://www.freesion.com/article/8678528786/
- 方法3 使用hutool工具包
- int转byte数组
- byte数组转int
- hutool依赖
方法1 自己写
int转byte数组
public static byte[] toHH(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
byte数组转int
public static int toInt(byte[] b){
int res = 0;
for(int i=0;i<b.length;i++){
res += (b[i] & 0xff) << ((3-i)*8);
}
return res;
}
参考:https://blog.csdn.net/qq_41054313/article/details/88424454
方法2 使用java NIO包的功能
int转byte数组
public static byte[] intToByteArray(int n) {
return ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(n).array();
}
byte数组转int
public static int byteArrayToInt(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put(bytes, 0, bytes.length);
buffer.flip();
return buffer.getInt();
}
参考:https://www.freesion.com/article/8678528786/
方法3 使用hutool工具包
int转byte数组
public static byte[] intToByteArray(int n) {
return ByteUtil.intToBytes(n, ByteOrder.BIG_ENDIAN);
}
byte数组转int
public static int byteArrayToInt(byte[] bytes) {
return ByteUtil.bytesToInt(bytes,ByteOrder.BIG_ENDIAN);
}
hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.15</version>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)