Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

unsigned

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?

like image 391
maerics Avatar asked Mar 06 '12 05:03

maerics


People also ask

How do you convert a signed integer to an unsigned integer?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

What is the difference between a signed integer and an unsigned integer?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.


1 Answers

Something like this?

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

Or am I missing something?

public static long getUnsignedInt(int x) {     return x & 0x00000000ffffffffL; } 
like image 69
Mysticial Avatar answered Sep 23 '22 17:09

Mysticial