public class IntToByteArrayExample {
public static void main(String[] args) {
int number = 123456; // 示例整数
// 方法1: 使用ByteBuffer
byte[] bytes1 = new java.nio.ByteBuffer.allocate(4).putInt(number).array();
System.out.println("使用ByteBuffer转换结果: " + bytesToHex(bytes1));
// 方法2: 手动转换
byte[] bytes2 = new byte[4];
bytes2[0] = (byte) (number >> 24);
bytes2[1] = (byte) (number >> 16);
bytes2[2] = (byte) (number >> 8);
bytes2[3] = (byte) number;
System.out.println("手动转换结果: " + bytesToHex(bytes2));
}
// 辅助方法:将字节数组转换为十六进制字符串,方便查看
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString().trim();
}
}
使用ByteBuffer:
ByteBuffer 是 Java NIO 中的一个类,用于处理字节缓冲区。allocate(4) 分配一个4字节的缓冲区(因为 int 类型占4个字节)。putInt(number) 将整数写入缓冲区。array() 将缓冲区的内容转换为字节数组。手动转换:
>> 是右移运算符,用于将整数的各个字节分离出来。(byte) number 获取。辅助方法 bytesToHex:
上一篇:java聊天室代码
下一篇:java四种锁机制
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站