如何对Ruby中的两个位串进行按位与运算?

How to bitwise AND two bit strings in Ruby?

我输入的数据是位串,假设是二进制数,每4个字节:

str  = "11111111010011111111111010000001"
str2 = "11000000000000000000000000000011"

我想使用按位与将两个字符串组合起来,就像这样

str & str2 #=> "11000000000000000000000000000001"

我尝试使用 str.to_i 将两个字符串都转换为整数,但 Ruby 将输入视为以 10 为底,而不是以 2 为底:

str.to_i #=> 11111111010011111111111010000001

我该如何解决这个问题?

以下代码应该可以满足您的需求:

str  = "11111111010011111111111010000001"
str2 = "11000000000000000000000000000011"

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

result.to_s(2)
=> "11000000000000000000000000000001"

您可以使用 to_i 从二进制表示法转换,并使用 to_s 通过将基数指定为参数来转换回二进制表示法。 2是二进制,8是八进制,16是十六进制。

例如这里的通用解决方案:

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

其中使用 map 将所有项目转换为整数,然后将它们与 & 组合成一个奇异值。然后将该值转换回以二为基数的字符串。

可以这样调用:

binary_add(
  "11111111010011111111111010000001",
  "11000000000000000000000000000011"
)

# => "11000000000000000000000000000001"

不与整数相互转换:

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

str中的每个1替换为str2中对应的字符。

$~ returns the match and begin它的索引。