java - 将两个整数保存为一个

标签 java integer hex bitwise-operators

将两个 int 保存为一个 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的范围只有从0到255的1个字节和从0到16777215的3个字节的sectorOffset)?

最佳答案

测试程序:

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 位,然后设置第二个数字。

关于java - 将两个整数保存为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770083/

相关文章:

javascript - 增加可为 null int 的值(int?)

c++ - printf 语句中的 0x%08lx 格式说明符到 cout

java - 如何使用 Collections.checkedlist

c - 验证输入 cmdline 输入 argv[] 包含所有整数

java - 如何确定加载类的绝对路径(如果有)?

c - 16 位短(实)跨步数据的 FFT

c++ - 在C++中将从文件读取的二进制数据转换为char指针

将十六进制转换为 float 并将 float 转换为十六进制

java - 将对象放入 ByteBuffer 而不对其进行序列化

java - 使用 ExecutorService 时获取对 Handler 的引用