无法从按位运算中获取长值

Unable to obtain long value from bitwise operation

我需要获取以下按位运算的输出,以便进一步处理。不幸的是,每当我尝试将输出转换为 int 或 long 类型时,我都会收到数字格式异常。如何确保我可以处理的类型的输出?

String TYPE = "type";
long TOTAL_MASK = 0xFFFFFFFF;
long BASE_INBOX_TYPE = 20;
long BASE_TYPE_MASK = 0x1F

long type = Integer.valueOf("" + TYPE + " & " + (TOTAL_MASK - BASE_TYPE_MASK) + " | " + BASE_OUTBOX_TYPE + "");

Integer.valueOf(String) 用于从文本中解析数字文字,而不是计算任意表达式。根据方法 javadoc:

The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method.

您需要将表达式写成代码,例如:

long type = (TOTAL_MASK - BASE_TYPE_MASK) | BASE_OUTBOX_TYPE;

一些运算符对单个操作数应用一元数值提升,它必须产生一个数值类型的值,如果操作数是编译时类型 byte、short 或 char,它会被提升为一个类型的值int 通过扩大原始转换 (§5.1.2)。

String TYPE = "type";
long TOTAL_MASK = 0xFFFFFFFF;
long BASE_INBOX_TYPE = ~20; // (~)promotion to int first (not necessary)
long BASE_TYPE_MASK = 0x1F;

long type = (TOTAL_MASK - BASE_TYPE_MASK) | BASE_INBOX_TYPE;

System.out.println(type);