将有符号整数转换为无符号长整型的最佳方法? [英] Best way to convert a signed integer to an unsigned long?

查看:468
本文介绍了将有符号整数转换为无符号长整型的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Java中的某些散列函数,将值视为无符号整数(例如,与其他实现进行比较)会很好,但Java仅支持有符号类型。我们可以将签名的 int 转换为unsigned long ,如下所示:

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?

推荐答案

这样的事情?

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

或者我错过了什么?

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

这篇关于将有符号整数转换为无符号长整型的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆