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?
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With