Best way to convert a signed integer to an unsigned long?

JavaUnsigned

Java Problem Overview


For certain hash functions in Java it would be nice to see the value as an unsigned integer (e.g. for comparison to other implementations) but Java supports only signed types. We can convert a signed int to an "unsigned" long as such:

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?

Java Solutions


Solution 1 - Java

Something like this?

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

Or am I missing something?

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

Solution 2 - Java

The standard way in Java 8 is Integer.toUnsignedLong(someInt), which is equivalent to @Mysticial's answer.

Solution 3 - Java

Guava provides UnsignedInts.toLong(int)...as well as a variety of other utilities on unsigned integers.

Solution 4 - Java

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. e.g.

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

For more examples of workarounds for using unsigned values. Unsigned utility class

Solution 5 - Java

other solution.

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

Solution 6 - Java

Just my 2 cents here, but I think it's a good practice to use:

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

instead of:

> return x & 0xFFFFFFFFL;

In this situation there's not your concern how many 'F's the mask has. It shall always work!

Solution 7 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmaericsView Question on Stackoverflow
Solution 1 - JavaMysticialView Answer on Stackoverflow
Solution 2 - JavasuperEbView Answer on Stackoverflow
Solution 3 - JavaLouis WassermanView Answer on Stackoverflow
Solution 4 - JavaPeter LawreyView Answer on Stackoverflow
Solution 5 - JavalmattView Answer on Stackoverflow
Solution 6 - JavaokoopatView Answer on Stackoverflow
Solution 7 - Javauser2207488View Answer on Stackoverflow