简体   繁体   English

将有符号整数转换为无符号长整型的最佳方法?

[英]Best way to convert a signed integer to an unsigned long?

For certain hash functions in Java it would be nice to see the value as an unsigned integer (eg for comparison to other implementations) but Java supports only signed types. 对于Java中的某些散列函数,将值视为无符号整数(例如,与其他实现进行比较)会很好,但Java仅支持有符号类型。 We can convert a signed int to an "unsigned" long as such: 我们可以将signed int转换为“unsigned” long ,如下所示:

public static final int BITS_PER_BYTE = 8;
public static long getUnsignedInt(int x) {
  ByteBuffer buf = ByteBuffer.allocate(Long.SIZE / BITS_PER_BYTE);
  buf.putInt(Integer.SIZE / BITS_PER_BYTE, x);
  return buf.getLong(0);
}
getUnsignedInt(-1); // => 4294967295

However, this solution seems like overkill for what we're really doing. 但是,这个解决方案对我们真正做的事情来说似乎有些过分。 Is there a more efficient way to achieve the same thing? 有没有更有效的方法来实现同样的事情?

Something like this? 像这样的东西?

int x = -1;
long y = x & 0x00000000ffffffffL;

Or am I missing something? 或者我错过了什么?

public static long getUnsignedInt(int x) {
    return x & 0x00000000ffffffffL;
}

Java 8中的标准方法是Integer.toUnsignedLong(someInt) ,这相当于@Mysticial的答案

Guava提供UnsignedInts.toLong(int) ...以及无符号整数上的各种其他实用程序。

You can use a function like 你可以使用像这样的功能

public static long getUnsignedInt(int x) {
    return x & (-1L >>> 32);
}

however in most cases you don't need to do this. 但在大多数情况下,您不需要这样做。 You can use workarounds instead. 您可以改用变通方法。 eg 例如

public static boolean unsignedEquals(int a, int b) {
    return a == b;
}

For more examples of workarounds for using unsigned values. 有关使用无符号值的变通方法的更多示例。 Unsigned utility class 未签名的实用程序类

other solution. 其他方案。

public static long getUnsignedInt(int x) {
    if(x > 0) return x;
    long res = (long)(Math.pow(2, 32)) + x;
    return res;
}

Just my 2 cents here, but I think it's a good practice to use: 这是我的2美分,但我认为这是一个很好的做法:

public static long getUnsignedInt(int x) { return x & (~0L); // ~ has precedence over & so no real need for brackets }

instead of: 代替:

return x & 0xFFFFFFFFL; return x&0xFFFFFFFFL;

In this situation there's not your concern how many 'F's the mask has. 在这种情况下,你不关心面具有多少'F'。 It shall always work! 它应该永远有效!

long abs(int num){
    return num < 0 ? num * -1 : num;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM