首页 > 解决方案 > 如何将整数放入给定位置的字节数组中?

问题描述

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

作为一个最小的示例,下面的代码尝试在字节数组的位置 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 直接复制到更大字节数组的给定位置。

标签: javaarraysbyte

解决方案


一种方法是使用 a ByteBuffer,它已经具有将 int 拆分为 4 个字节的逻辑:

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

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

int x = 542323;
byte b1 = (x >> 24) & 0xff;
byte b2 = (x >> 16) & 0xff;
byte b3 = (x >> 8) & 0xff;
byte b4 = x & 0xff;

// or the other way around, depending on byte order 
array[10] = b4;
array[11] = b3;
array[12] = b2;
array[13] = b1;

推荐阅读