2

The input data I have are bit strings, assumed to be a binary numbers, each 4 bytes:

str  = "11111111010011111111111010000001"
str2 = "11000000000000000000000000000011"

And I would like to combine the two strings using a bitwise AND, like so

str & str2 #=> "11000000000000000000000000000001"

I have tried converting both strings to integers using str.to_i but Ruby treats the input as base 10, rather than base 2:

str.to_i #=> 11111111010011111111111010000001

How can I solve this?

3
  • stackoverflow.com/a/2340415/525478 Commented Dec 12, 2017 at 19:44
  • 2
    Hint: String#to_i accepts parameter. Commented Dec 12, 2017 at 19:44
  • What number does 11111111010011111111111010000001 represent? Commented Dec 13, 2017 at 13:23

3 Answers 3

4

The following code should do what you are looking for:

str  = "11111111010011111111111010000001"
str2 = "11000000000000000000000000000011"

result = str.to_i(2) & str2.to_i(2)

result.to_s(2)
=> "11000000000000000000000000000001"
Sign up to request clarification or add additional context in comments.

Comments

3

You can use to_i to convert from binary notation and to_s to convert back to it by specifying the base as an argument. 2 is binary, 8 is octal, 16 is hex.

For example a generic solution here:

def binary_add(*items)
  items.map { |i| i.to_i(2) }.reduce(:&).to_s(2)
end

Where that uses map to convert all the items to integers, then combines those together with & into a singular value. That value's then converted back to a base-two string.

Which can be called like this:

binary_add(
  "11111111010011111111111010000001",
  "11000000000000000000000000000011"
)

# => "11000000000000000000000000000001"

Comments

2

Without converting to and from integer:

str.gsub('1') { str2[$~.begin(0)] }
#=> "11000000000000000000000000000001"

It replaces each 1 in str with the corresponding character in str2.

$~ returns the match and begin its index.

Comments

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.