我正在使用Ruby gem Bindata,使用以下代码:
require 'bindata'
class Rectangle < BinData::Record
endian :little
uint16 :len
string :name, :read_length => :len
uint32 :width
uint32 :height
end
rectangle = rectangle.new
rectangle.len = 12
可以从rectangle
实例中获得类似[0, 1, 1, 0, 0, ...]
的数组,该数组具有对象内所有字段的二进制表示?
BinData::Base#to_binary_s
返回"此数据对象的字符串表示":
rectangle.to_binary_s
#=> "fx00x00x00x00x00x00x00x00x00"
可以通过String#unpack
:将其转换为比特串
rectangle.to_binary_s.unpack('b*')
#=> ["00110000000000000000000000000000000000000000000000000000000000000000000000000000"]
或者通过:连接到位阵列
rectangle.to_binary_s.unpack('b*')[0].chars.map(&:to_i)
#=> [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]