XOR two binary strings

G

Gary Chris

Howdy,

I am having difficulty finding how to XOR 2 binary strings.
Is there a builtin function for this ?
Something like
return string_one ^ string_two

Thanks
 
J

Jan-Erik R.

Gary said:
Howdy,

I am having difficulty finding how to XOR 2 binary strings.
Is there a builtin function for this ?
Something like
return string_one ^ string_two

Thanks
what do you mean by binary Strings?
"011101"?
use
Integer("0b#{binarystring}")
to convert it to an integer, then use the XOR and later use
String#to_s(2)
to convert it back again.
 
J

Joel VanderWerf

Gary said:
Howdy,

I am having difficulty finding how to XOR 2 binary strings.
Is there a builtin function for this ?
Something like
return string_one ^ string_two

Thanks

All I can think of at the moment:

a = [0b00000001, 0b00001000].pack("C*")
b = [0b10000001, 0b01000000].pack("C*")

c = a.unpack("C*").zip(b.unpack("C*"))
c = c.map {|x,y| x^y}
c = c.pack("C*")
p c
 
R

Robert Klemme

Gary said:
Howdy,

I am having difficulty finding how to XOR 2 binary strings.
Is there a builtin function for this ?
Something like
return string_one ^ string_two

Thanks

All I can think of at the moment:

a = [0b00000001, 0b00001000].pack("C*")
b = [0b10000001, 0b01000000].pack("C*")

c = a.unpack("C*").zip(b.unpack("C*"))
c = c.map {|x,y| x^y}
c = c.pack("C*")
p c

There's also

irb(main):002:0> ("00000001".to_i(2) ^ "0110".to_i(2)).to_s(2)
=> "111"

Kind regards

robert
 
B

Brian Candler

I'm not sure if "binary string" meant a string of the form "000101...",
or if it meant two strings treated as arrays of bytes.

If the latter, then

irb(main):001:0> require 'enumerator'
=> true
irb(main):002:0> s1 = "abc".to_enum:)each_byte)
=> #<Enumerable::Enumerator:0xb7cc85dc>
irb(main):003:0> s2 = "\x02\x04\x06".to_enum:)each_byte)
=> #<Enumerable::Enumerator:0xb7cc02c4>
irb(main):004:0> s1.zip(s2).map{ |x,y| (x^y).chr }.join
=> "cfe"

ruby 1.9 lets you shorten this to

irb(main):001:0> "abc".bytes.zip("\x02\x04\x06".bytes).map { |x,y|
(x^y).chr }.join
=> "cfe"
 
S

Sandor Szücs

am having difficulty finding how to XOR 2 binary strings.
Is there a builtin function for this ?
Something like
return string_one ^ string_two

There is also facets:

irb> require 'facets/string/xor'
irb> "\000\000\001\001" ^ "\000\001\000\001" # =3D> "\000\001\001\000"


Hth. regards, Sandor Sz=FCcs
--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top