简体   繁体   English

java long数据类型转换为无符号值

[英]java long datatype conversion to unsigned value

I'm porting some C++ code to Java code. 我正在将一些C ++代码移植到Java代码。

There is no unsigned datatype in java which can hold 64 bits. Java中没有可容纳64位的无符号数据类型。

I have a hashcode which is stored in Java's long datatype (which of course is signed). 我有一个存储在Java的long数据类型(当然是带符号的)中的哈希码。

long vp = hashcode / 38; // hashcode is of type 'long'

Since 38 here is greater than 2, the resulting number can be safely used for any other arithmetic in java. 由于此处的38大于2,因此可以安全地将所得结果数用于java中的任何其他算术。

The question is what if the signed bit in 'hashcode' is set to 1. I don't want to get a negative value in variable vp. 问题是,如果“哈希码”中的有符号位设置为1,该怎么办?我不想在变量vp中获得负值。 I wanted a positive value as if the datatype is an unsigned one. 我想要一个正值,好像数据类型是无符号的。

PS: I don't want to used Biginteger for this purpose because of performance issues. PS:由于性能问题,我不想将Biginteger用于此目的。

Java's primative integral types are considered signed, and there isn't really anything you can do about it. Java的原始整数类型被认为是带符号的,您实际上对此无能为力。 However, depending on what you need it for, this may not matter. 但是,根据您的需要,这可能并不重要。

Since the integers are all done in two's complement, signed and unsigned are exact same at the binary level. 由于所有整数都是以二进制补码完成的,因此有符号和无符号在二进制级别完全相同。 The difference is how you interpret them, and in certain operations. 区别在于您在特定操作中的解释方式。 Specifically, right shift, division, modulus and comparison differ. 具体来说,右移,除法,模数和比较有所不同。 Unsigned right shifts can be done with the >>> operator. 可以使用>>>运算符进行无符号右移。 As long as you don't need one of the missing operators, you can use long s perfectly well. 只要您不需要缺少的运算符之一,就可以很好地使用long

If you can use third-party libraries, you can eg use Guava's UnsignedLongs class to treat long values as unsigned for many purposes, including division. 如果可以使用第三方库,则可以使用Guava的UnsignedLongs类将long值视为无符号的多种用途,包括除法。 (Disclosure: I contribute to Guava.) (公开:我为番石榴做出了贡献。)

Well here is how i solved this. 好吧,这就是我解决这个问题的方式。 Right shift hashcode by 1 bit(division by 2). 右移哈希码1位(除以2)。 Then divide that right shifted number by 19(which is 38/2). 然后将右移的数字除以19(即38/2)。 So essentially i divided the number by 38 exactly like how it is done in c++. 因此,基本上我将数字除以38完全像在c ++中一样。 I got the same value what i got in c++ 我得到了与C ++相同的价值

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

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