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?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Kev
  • 47
  • 4

3 Answers3

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"
simplaY
  • 161
  • 4
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"
tadman
  • 208,517
  • 23
  • 234
  • 262
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.

Stefan
  • 109,145
  • 14
  • 143
  • 218