我如何在给定位置的字节数组中放入整数?

问题描述 投票:0回答:1

我想在给定位置用变量填充字节数组。

作为最小的示例,下面的代码尝试在字节数组的位置10插入int变量(它将使用字节数组的字节10、11、12和13)。

public class HelloWorld{

     public static void main(String []args){

       // DESTIONATION BYTE ARRAY
       byte[] myByteArray = new byte[64];

       // INTEGER
       int myInt = 542323;

       // I WANT TO PUT myInt AT POSITION 10 IN myByteArray
       // PSEUDOCODE BELOW:
       myByteArray.putInt(myInt, 10);

     }
}

我不确定我必须将哪些int直接复制到较大字节数组的给定位置。

java arrays byte
1个回答
0
投票

执行此操作的一种方法是使用ByteBuffer,该逻辑已经具有将int拆分为4个字节的逻辑:

ByteBuffer

当然,这会创建一个额外的字节数组和字节缓冲区对象,如果仅使用位掩码,则可以避免这种情况:

byte[] array = new byte[64];

ByteBuffer buffer = ByteBuffer.allocate(4);
// buffer.order(ByteOrder.nativeOrder()); // uncomment if you want native byte order
buffer.putInt(542323);

System.arraycopy(buffer.array(), 0, array, 10, 4);
//                                         ^^
//                        change the 10 here to copy it somewhere else
© www.soinside.com 2019 - 2024. All rights reserved.