【问题标题】:Combine 2 (signed) Integers into one将 2 个(有符号)整数合二为一
【发布时间】: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 就足够了,而且更容易阅读
  • 谢谢,不知道那个选项。

标签: java integer bit-shift


【解决方案1】:

这是我经过一些测试后得到的,假设正整数不超过 127,负整数不小于 -128:

public static int encodeInt(int key, int value) {
    return (key << 8) | (value < 0 ? value + 256 : value);
}
public static int decodeInt1(int combined) {
    return combined >> 8;
}
public static int decodeInt2(int combined) {
    combined &= 0xFF;
    return combined < 128 ? combined : combined - 256;
}

产生:

encodeInt(0, 0) // 0
encodeInt(0, 20) // 20
encodeInt(0, 127) // 127
encodeInt(0, -128) // 128

encodeInt(1, 0) // 256
encodeInt(1, 20) // 276
encodeInt(1, 127) // 383
encodeInt(1, -128) // 384

等等…… 仅适用于整数范围 -128 - +127,因为 +128 将在 decodeInt2 上转换为 -128。

这是个好方法吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多