Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bitwise AND two bit strings in Ruby?

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?

like image 357
Kev Avatar asked Jan 21 '26 15:01

Kev


2 Answers

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"
like image 94
simplaY Avatar answered Jan 23 '26 05:01

simplaY


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"
like image 30
tadman Avatar answered Jan 23 '26 06:01

tadman