How to perform XOR operation between two hexadecimal strings?

I have two hexadecimal strings. I need to perform an XOR operation between them.

My hexadecimal strings are like,

  a = "1A6F2D31567C80644A5BEF2D50B986B"; b = "EF737F481FC7CDAE7C8B40837C80644"; 

How to do XOR operation between them? Can you give some recommendations for this?

+7
source share
3 answers

This will work for any base:

 >> (a.to_i(16) ^ b.to_i(16)).to_s(16) => "f51c527949bb4dca36d0afae2c39e2f" 

But you can use String # hex for hexadecimal strings.

+12
source
 a = "1A6F2D31567C80644A5BEF2D50B986B" b = "EF737F481FC7CDAE7C8B40837C80644" a.hex ^ b.hex #or (a.hex ^ b.hex).to_s(16) 
+9
source

You didn’t specifically ask the question, but you may need the output line to be the same as the input lines, using fill leading zeros . So, relying on steenslag slick answer (and adjusting the input values ​​to illustrate a potential problem):

 a = "14ef" b = "1ca3" (a.hex ^ b.hex).to_s(16) # "84c" (a.hex ^ b.hex).to_s(16).rjust(a.length, '0') # "084c" 
+1
source