将两个整数保存为一个
Saving two ints into one
2个int存为1个int的具体说明如下:
The bottom byte contains how many sectors the chunk uses. The other 3
bytes are containing the offset to the chunk-sector.
所以如果我想提取我的两个数字,我必须这样做
int usedSectors = num & 0xFF;
int sectorOffset = num >> 8;
但是我怎样才能将两个整数保存到那个整数中,例如我已经给出了 usedSectors 和 sectorOffset(我们假设 usedSectors 的范围只有 1 个字节,从 0 到 255,sectorOffset 的范围是 3 个字节,从 0 到 16777215)?
aggrigaated_int=0;
aggrigaated_int+=first_num;
aggrigaated_int+=second_num <<8;
测试程序:
public class ByteTest {
public static void main(String[] args) {
int expectedUsedSectors = 4;
int expectedSectorOffset = 20000;
int num = expectedSectorOffset;
num = num << 8;
num |= expectedUsedSectors;
int usedSectors = num & 0xFF;
int sectorOffset = num >> 8;
System.out.println("used sectors expected == actual? " + (expectedUsedSectors == usedSectors));
System.out.println("offset expected == actual? " + (expectedSectorOffset == sectorOffset));
}
}
首先我设置了 3 个字节的值然后移动 8 位然后设置第二个数字。
2个int存为1个int的具体说明如下:
The bottom byte contains how many sectors the chunk uses. The other 3 bytes are containing the offset to the chunk-sector.
所以如果我想提取我的两个数字,我必须这样做
int usedSectors = num & 0xFF;
int sectorOffset = num >> 8;
但是我怎样才能将两个整数保存到那个整数中,例如我已经给出了 usedSectors 和 sectorOffset(我们假设 usedSectors 的范围只有 1 个字节,从 0 到 255,sectorOffset 的范围是 3 个字节,从 0 到 16777215)?
aggrigaated_int=0;
aggrigaated_int+=first_num;
aggrigaated_int+=second_num <<8;
测试程序:
public class ByteTest {
public static void main(String[] args) {
int expectedUsedSectors = 4;
int expectedSectorOffset = 20000;
int num = expectedSectorOffset;
num = num << 8;
num |= expectedUsedSectors;
int usedSectors = num & 0xFF;
int sectorOffset = num >> 8;
System.out.println("used sectors expected == actual? " + (expectedUsedSectors == usedSectors));
System.out.println("offset expected == actual? " + (expectedSectorOffset == sectorOffset));
}
}
首先我设置了 3 个字节的值然后移动 8 位然后设置第二个数字。