如何在位串中转换位数组,其中每个位代表 Ruby 中的一个布尔值
How do I turn an array of bits in an bitstring where each bit represents one boolean in Ruby
这个问题不言自明。我想将 [true, true, false, true]
之类的内容转换为以下位串 1101.
我想我需要使用 Array.pack,但我不知道具体怎么做。
您可以为 TrueClass
和 FalseClass
定义一个 to_i
方法。像这样:
class TrueClass
def to_i
1
end
end
class FalseClass
def to_i
0
end
end
[true, true, false, true].map(&:to_i).join
# => "1101"
这实际上取决于您想要表示布尔数组的精确程度。
对于[true, true, false, true]
,应该是0b1101
还是0b11010000
?我假设是前者,你可能会这样理解:
data = [true, true, false, true]
out = data
.each_slice(8) # group the data into segments of 8 bits, i.e., a byte
.map {|slice|
slice
.map{|i| if i then 1 else 0 end } # convert to 1/0
.join.to_i(2) # get the byte representation
}
.pack('C*')
p out #=> "\r"
PS。根据您的要求,可能还有其他字节序问题。
ary = [true, true, false, true]
ary.map { |b| b ? 1.chr : 0.chr }.join
#=> "\x01\x01\x00\x01"
你确实可以用 pack
首先将布尔值转换为字符串
bit_string = [true, false, false,true].map {|set| set ? 1 :0}.join
如果需要,用零填充字符串
bit_string = "0" * (8 - (bit_string.length % 8)) + bit_string if bit_string.length % 8 != 0
然后打包
[bit_string].pack("B*")
这个问题不言自明。我想将 [true, true, false, true]
之类的内容转换为以下位串 1101.
我想我需要使用 Array.pack,但我不知道具体怎么做。
您可以为 TrueClass
和 FalseClass
定义一个 to_i
方法。像这样:
class TrueClass
def to_i
1
end
end
class FalseClass
def to_i
0
end
end
[true, true, false, true].map(&:to_i).join
# => "1101"
这实际上取决于您想要表示布尔数组的精确程度。
对于[true, true, false, true]
,应该是0b1101
还是0b11010000
?我假设是前者,你可能会这样理解:
data = [true, true, false, true]
out = data
.each_slice(8) # group the data into segments of 8 bits, i.e., a byte
.map {|slice|
slice
.map{|i| if i then 1 else 0 end } # convert to 1/0
.join.to_i(2) # get the byte representation
}
.pack('C*')
p out #=> "\r"
PS。根据您的要求,可能还有其他字节序问题。
ary = [true, true, false, true]
ary.map { |b| b ? 1.chr : 0.chr }.join
#=> "\x01\x01\x00\x01"
你确实可以用 pack
首先将布尔值转换为字符串
bit_string = [true, false, false,true].map {|set| set ? 1 :0}.join
如果需要,用零填充字符串
bit_string = "0" * (8 - (bit_string.length % 8)) + bit_string if bit_string.length % 8 != 0
然后打包
[bit_string].pack("B*")