0

I have an array of long(45) character bitstrings, that basically represent the boolean state of a bunch of attributes. I need to perform OR and AND operations on these strings and get back the resulting binary string. ex:

    a = "100"
    b = "101"

I now need to compute:

    a_or_b  = "101"
    a_and_b = "100"

Is there efficient anyway for me to do this? Can I use the bitwise operators somehow?

1 Answer 1

2

You have Integer#to_s(base) and String.to_i(base) available to you.

a_and_b = (a.to_i(2) & b.to_i(2)).to_s(2)

a_or_b = (a.to_i(2) | b.to_i(2)).to_s(2)

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, thanks! I am a bit of a noob in this area, so forgive me if this is stupid. But will this be faster than looping? Are the to binary and back to string operations expensive?
I do not think loop would be faster. As the Ruby basic apis are implemented in C, which should be faster than Ruby code itself.
Great, thank you. I did some quick benchmarking and the results were stunning. For 50,000 iters, the binary operations took 0.11 secs and the same thing with a ruby loop took 2.71 seconds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.