如何连接 java 中的两个字节?

How can I concatenate two bytes in java?

我有一个名为 writePos 的整数,它的值介于 [0,1023] 之间。我需要将它存储在名为 bucket 的字节数组的最后两个字节中。所以,我想我需要将它表示为数组最后两个字节的串联。

  1. 我如何将 writePos 分解为两个字节,当连接并转换为 int 时,会再次产生 writePos

  2. 一旦我将它分解成字节,我将如何进行连接?

位运算。

至字节:

byte[] bytes = new byte[2];
// This uses a bitwise and (&) to take only the last 8 bits of i
byte[0] = (byte)(i & 0xff); 
// This uses a bitwise and (&) to take the 9th to 16th bits of i
// It then uses a right shift (>>)  then move them right 8 bits
byte[1] = (byte)((i & 0xff00) >> 8);from byte:

从另一个方向回去

// This just reverses the shift, no need for masking.
// The & here is used to handle complications coming from the sign bit that
// will otherwise be moved as the bytes are combined together and converted
// into an int
i = (byte[0] & 0xFF)+(byte[1] & 0xFF)<<8;

这里有一个您可以尝试的一些转换的工作示例: http://ideone.com/eRzsun

您需要将整数拆分为两个字节。高字节和低字节。按照您的描述,它在数组中存储为错误字节序。

int writeLocation = 511;
byte[] bucket = new byte[10];
// range checks must be done before
// bitwise right rotation by 8 bits
bucket[8] = (byte) (writeLocation >> 8); // the high byte
bucket[9] = (byte) (writeLocation & 0xFF); // the low byte

System.out.println("bytes = " + Arrays.toString(bucket));

// convert back the integer value 511 from the two bytes
bucket[8] = 1;
bucket[9] = (byte) (0xFF);
// the high byte will bit bitwise left rotated
// the low byte will be converted into an int
// and only the last 8 bits will be added
writeLocation = (bucket[8] << 8) + (((int) bucket[9]) &  0xFF);
System.out.println("writeLocation = " + writeLocation);

这将由 ByteBuffer 进行高级处理。

short loc = (short) writeLocation;

byte[] bucket = ...
int idex = bucket.length - 2;
ByteBuffer buf = ByteBuffer.wrap(bucket);
buf.order(ByteOrder.LITTLE__ENDIAN); // Optional
buf.putShort(index, loc);

writeLocation = buf.getShort(index);

可以指定顺序,也可以保留默认顺序(BIG_ENDIAN)。

  1. ByteBuffer包裹了原来的byte数组,改成ByteBuffer对byte数组也有影响
  2. 可以使用顺序写入和读取定位(查找),但这里我使用重载方法进行立即定位 index
  3. putShort写入字节数组,修改两个字节,一个short。
  4. getShort从字节数组中读取一个short,可以放入一个int中。

解释

java中的一个short是一个双字节(有符号)整数。这就是意思。顺序是LITTLE_ENDIAN: least significant byte first (n % 256, n / 256) or big endian.