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

maerics picture maerics · Mar 6, 2012 · Viewed 68.2k times · Source

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?

Answer

Mysticial picture Mysticial · Mar 6, 2012

Something like this?

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

Or am I missing something?

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