Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise XOR java long

I am using Oracle Java 7.51 on Ubuntu 12.04, and trying to do this

long a = 0x0000000080000001 ^ 0x4065DE839A6F89EEL;
System.out.println("result "+ Long.toHexString(a));

Output: result bf9a217c1a6f89ef

But I was expecting result to be 4065de831a6f89ef, since ^ operator is a bitwise XOR in Java. Which part of Java specification am I reading wrong?

like image 274
Soham Avatar asked Mar 26 '14 04:03

Soham


1 Answers

You need an L at the end of the first integer literal:

long a = 0x0000000080000001L ^ 0x4065DE839A6F89EEL;

Otherwise it is an int literal, not a long (the leading zeroes being ignored). The ^ operator then promotes the first operand value from 0x80000001 to a long, but since the sign bit is set, the result of the promotion is 0xFFFFFFFF80000001L.

like image 158
Ted Hopp Avatar answered Oct 18 '22 00:10

Ted Hopp