我有一个名为writePos
的整数,其值介于[0,1023]
之间。我需要将它存储在名为bucket
的字节数组的最后两个字节中。所以,我想我需要将它表示为数组最后两个字节的串联。
我如何将writePos
分解为两个字节,当连接并强制转换为int
时,会再次生成writePos
?
一旦我将其分解为字节,我将如何进行连接?
答案 0 :(得分:2)
这将由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)。
index
进行即时定位。putShort
写入字节数组,修改两个字节,简短。getShort
从字节数组读取一个short,可以放入int。<强> 解释 强>
java中的short
是一个双字节(带符号)整数。这就是意思。顺序是LITTLE_ENDIAN:最低有效字节优先(n%256,n / 256)还是大端。
答案 1 :(得分:1)
按位操作。
字节:
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
答案 2 :(得分:0)
您需要将整数拆分为两个字节。高字节和低字节。根据您的描述,它将作为bug endian存储在数组中。
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);