lkawon
lkawon

Reputation: 49

XOR between floats in python

I am implementing conversion from RGB to Yxy color and the pseudocode guides me to execute XOR (^) operation on two float variables. How I can do this in python? I get this error:

unsupported operand type(s) for ^: 'float' and 'float'

Take a look at this pseudocode: http://www.easyrgb.com/index.php?X=MATH&H=02#text2.

Upvotes: 1

Views: 4967

Answers (3)

CoderBoy
CoderBoy

Reputation: 107

import struct, math

def fxor(a, b):
  rtrn = []
  a = struct.pack('d', a)
  b = struct.pack('d', b)
  for ba, bb in zip(a, b):
    rtrn.append(ba ^ bb)

  return struct.unpack('d', bytes(rtrn))[0]

print(fxor(math.pi, math.pi)) #0.0
print(fxor(math.e, math.pi))  #1.7551491316820714e-308
print(fxor(math.pi, 0))       #3.141592653589793

64-bit float xor. This performs an xor operation on each bit that makes up the floating point and returns it as a double and/or 64-bit float

Upvotes: 0

Abhijit
Abhijit

Reputation: 63767

There is no inbuilt support for xoring floating point numbers. Instead you have to implement one using the struct module

>>> from struct import pack, unpack
>>> def xor_float(f1, f2):
    f1 = int(''.join(hex(ord(e))[2:] for e in struct.pack('d',f1)),16)
    f2 = int(''.join(hex(ord(e))[2:] for e in struct.pack('d',f2)),16)
    xor = f1 ^ f2
    xor = "{:016x}".format(xor)
    xor = ''.join(chr(int(xor[i:i+2],16)) for i in range(0,len(xor),2))
    return struct.unpack('d',xor)[0]

>>> xor_float(10.25,10.25)
0.0
>>> xor_float(10.25,0.00)
10.25

Note This example assumes, that the floating point number is a 64 bit float, as natively supported by Python


I should have seen your pseudo-code before jumping in to solving this problem. The caret ^ in the pseudo-code is power rather than xor and in python raising a number to power (including float) is done through ** or math.pow

Upvotes: 4

Peter Wooster
Peter Wooster

Reputation: 6089

You can only apply bit wise operators to integers. So convert the floats to integer first.

Upvotes: 0

Related Questions