7

How to XOR two doubles in JAVA?

simple '^' doesn't work for doubles... Would I have to convert a double to binary form and do it bitwise? or is there any other way?

Eternal Noob
  • 2,677
  • 5
  • 24
  • 40
  • 2
    Can't think of a nice way to do this, but I'm kind of curious about why you would want to do that in the first place... can you enlighten me? – user507787 Nov 18 '10 at 02:25
  • Since XOR is a bitwise operator, it's usually applied only to integers. Do you really want to try to bitwise XOR doubles (which could lead to _really_ weird results) or do you just want to work with ints? – Matt Ball Nov 18 '10 at 02:26
  • I am implementing a compression algorithm for a stream of doubles, and that algorithm requires XORing two consecutive numbers. – Eternal Noob Nov 18 '10 at 02:27
  • This might be useful simply for hashing purposes. But in that case be aware that comparisons to NaN are very unexpected in Java. They are always false. –  Mar 22 '16 at 17:57

1 Answers1

14

If you mean to do this bitwise you need to use the Double utility functions to get long representations and then convert back to a double at the end:

double c = Double.longBitsToDouble(
    Double.doubleToRawLongBits(a) ^ Double.doubleToRawLongBits(b));
Mark Elliot
  • 72,164
  • 19
  • 138
  • 159
  • 2
    Never convert the XOR-ed long back to double, because there are many bit patterns that lead to NaN, +infinity and -infinity and many other sets of bit patterns that represent the same number (one cacnonical, the rest denormal, the most common ones being +0 and -0, +0e1, +0e2, etc) – Mark Jeronimus Oct 03 '18 at 07:19