Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XORing two double variables

Tags:

c++

double

xor

I wrote the following two lines :

Line 1 :

int a;
a=a^a;

Line 2 :

double d;
d=d^d;

Line 1 Works Fine But Line 2 Gives Me Error :

error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator^’

Can Somebody tell me why the bit-wise XOR operator works on two int but doesn't work on two double variables...??

Seems like a silly doubt...but i really couldn't get through my program without this...!

like image 536
Rohith R Avatar asked Jun 24 '14 08:06

Rohith R


2 Answers

Because the standard says so.

C++11 §5.12 Bitwise exclusive OR operator

The usual arithmetic conversions are performed; the result is the bitwise exclusive OR function of the operands. The operator applies only to integral or enumeration operands.

And it doesn't make much sense to xor two doubles, in my opinion.

like image 77
Yu Hao Avatar answered Nov 10 '22 09:11

Yu Hao


I think the other answers explained pretty well why its not supported by default. You should probably not do it, but here's how you can do it:

    double d = 12345.6789;
    unsigned long long* uPtr = (unsigned long long*)&d;
    unsigned long long uXor = (*uPtr) ^ (*uPtr);
    double dXor = *((double*)&uXor);

like image 41
user2888798 Avatar answered Nov 10 '22 11:11

user2888798