简体   繁体   中英

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

I have some code in C++ that I'm trying to port over to Java and there is a problem I can't solve.

It's easily seen with an example. At some stage in the C++ code, I have an unsigned int h with a value of 594076817. I then compute (h << 10). I get the result 2744271872.

In Java, I have a long 594076817. I then compute (h << 10) and I get 608334660608.

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

The C++ code appears to be operating on 32-bit ints. Using Java's 32-bit integer type int , the code

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

prints -1550695424 (Java's int s are signed). This is 2744271872 - 2 32 . When the datatype is changed to the 64-bit integer type long , the answer changes:

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

This prints 608334660608 . When you truncate everything beyond the lower 32 bits of 608334660608 , you get the int answer: 2744271872 .

To get the desired result, which seems to rely on overflow in C++, use long in Java, but bit-mask out the last 32 bits by bit-anding with 0xFFFFFFFFL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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