我有一个名为writePos
的整数,它取值范围在[0, 1023]
之间。我需要将其存储在名为bucket
的字节数组的最后两个字节中。因此,我认为我需要将其表示为数组的最后两个字节的连接。
我该如何将
writePos
拆分成两个字节,在将其串联并转换为int
时,可以再次生成writePos
?一旦我将其拆分为字节,我该如何进行连接?
我有一个名为writePos
的整数,它取值范围在[0, 1023]
之间。我需要将其存储在名为bucket
的字节数组的最后两个字节中。因此,我认为我需要将其表示为数组的最后两个字节的连接。
我该如何将writePos
拆分成两个字节,在将其串联并转换为int
时,可以再次生成writePos
?
一旦我将其拆分为字节,我该如何进行连接?
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;
byte[] bytes = new byte[2];byte[0] = (byte)i;byte[1] = (byte)(i >>> 8);
是可以的,因为从int到byte的赋值不会改变任何位。 - fredtshort 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)。
putShort
将两个字节(一个short)写入字节数组并进行修改。getShort
从字节数组中读取一个short,该short可以放入int中。说明
在Java中,short
是一个两个字节(有符号)整数。这就是其含义。顺序是指LITTLE_ENDIAN:最低有效字节先(n % 256, n / 256)还是big endian。
short
被定义为2个字节,而不是int
。 - Joop Eggenint 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);
DataOutputStream
和DataInputStream
。 - user207421