Java中从Integer和Long变量提取原始数据的方法
将Integer和Long转换为字节数组的方法
1. Integer 转字节数组
方法一:使用 ByteBuffer(推荐)
借助Java NIO的ByteBuffer类可以快速实现转换,代码简洁且不易出错:
Integer intValue = 42; byte[] intBytes = ByteBuffer.allocate(Integer.BYTES).putInt(intValue).array();
allocate(Integer.BYTES)会分配4字节的缓冲区,putInt写入int值后,array()直接返回底层的字节数组。
方法二:手动位运算
如果需要自定义字节顺序(大端/小端),可以通过位运算手动拆分:
Integer intValue = 42; byte[] intBytes = new byte[4]; // 大端模式(高位字节在前,Java默认内存布局) intBytes[0] = (byte) (intValue >> 24); intBytes[1] = (byte) (intValue >> 16); intBytes[2] = (byte) (intValue >> 8); intBytes[3] = (byte) intValue; // 若需要小端模式,调整字节顺序: // intBytes[0] = (byte) intValue; // intBytes[1] = (byte) (intValue >> 8); // intBytes[2] = (byte) (intValue >> 16); // intBytes[3] = (byte) (intValue >> 24);
2. Long 转字节数组
方法一:使用 ByteBuffer(推荐)
逻辑与Integer转换一致,利用ByteBuffer简化操作:
Long longValue = 9876543210L; byte[] longBytes = ByteBuffer.allocate(Long.BYTES).putLong(longValue).array();
方法二:手动位运算
手动拆分8字节的long值:
Long longValue = 9876543210L; byte[] longBytes = new byte[8]; // 大端模式 longBytes[0] = (byte) (longValue >> 56); longBytes[1] = (byte) (longValue >> 48); longBytes[2] = (byte) (longValue >> 40); longBytes[3] = (byte) (longValue >> 32); longBytes[4] = (byte) (longValue >> 24); longBytes[5] = (byte) (longValue >> 16); longBytes[6] = (byte) (longValue >> 8); longBytes[7] = (byte) longValue; // 小端模式反转字节顺序即可
补充说明
ByteBuffer默认采用大端字节序,如果需要小端序,可在分配缓冲区后调用order(ByteOrder.LITTLE_ENDIAN)。- 手动位运算时,
>>为算术右移(负数会填充符号位),若需无符号右移可使用>>>,但处理原始数据时通常用算术右移即可。
内容的提问来源于stack exchange,提问作者Aakash Patel
相关产品推荐
相关产品推荐

