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

落爺英雄遲暮 提交于 2019-11-26 21:59:04

Something like this?

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

Or am I missing something?

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

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

Louis Wasserman

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

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

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:

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!

long abs(int num){
    return num < 0 ? num * -1 : num;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!