Bit shift difference in Java and C ++ - how to reconcile

I have some code in C ++ that I am trying to pipe to Java and there is a problem that I cannot solve.

This is easily seen in an example. At some point in the C ++ code, I have an unsigned int h with a value of 594076817. Then I calculate (h <<10). I get the result 2744271872.

In Java I have a long 594076817. Then I calculate (h <<10) and get 608334660608.

I understand / suspect this is due to differences in representation (unsigned vs signed) and tried to read these lines to no avail. What is the best way to get Java code to get the same result as C ++ code?

+3


source to share


1 answer


C ++ code works on 32 bit int. Using Java 32 bit integer type int

, the code

int h = 594076817;
System.out.println(h << 10);

      

prints -1550695424

(Java int

signed). This 2744271872

is 2 32 . When the data type changes to 64-bit integer type long

, the answer changes:



long h = 594076817L;
System.out.println(h << 10);

      

Will print 608334660608

. When you truncate all but the lower 32 bits 608334660608

, you get an answer int

: 2744271872

.

To get the desired result, which seems to rely on overflow in C ++, use long

in Java, but a bitmask of the last 32 bits over a bit-join with 0xFFFFFFFFL

.

+7


source







All Articles