【发布时间】:2015-03-07 20:32:36
【问题描述】:
使用 android java 我需要组合/解码 2 个整数,其中第二个可以签名。第一个整数是无符号的 0-4(4 位),第二个整数是从 -128 到最大 99。 为此,我在这里使用 HighCommander4 描述的操作: Combine two integers into one and decode them later
例如,结合
int id1 = 1;
int id2 = 20; // gives combined = 276
这是使用 HighCommander4s 解决方案的简单事情。 但是如何使用有符号整数来做到这一点:
int id1 = 1;
int id2 = -128; // gives combined = -384
现在基于上面链接的解决方案,我创建了以下函数:
public static int encodeInt(int key, int value) {
return ((key << 8) | (value < 0 ? value * -1 : value)) * (value < 0 ? -1 : 1);
}
public static int decodeInt1(int combined) {
return combined < 0 ? (combined * -1) >> 8 : combined >> 8;
}
public static int decodeInt2(int combined) {
return combined < 0 ? ((combined * -1) & 0xFF) * -1 : combined & 0xFF;
}
我对位移运算不是很熟悉,所以我认为会有更好的方法来组合有符号整数?
最好的问候, 于尔根
【问题讨论】:
-
为什么是
value * -1?只需-value就足够了,而且更容易阅读 -
谢谢,不知道那个选项。