I'm using Ruby gem Bindata, using the following code:

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

It is possible to get from rectangle instance an array like [0, 1, 1, 0, 0, ...] with the binary representation of all the fields inside the object?

有帮助吗?

解决方案

BinData::Base#to_binary_s returns "the string representation of this data object":

rectangle.to_binary_s
#=> "\f\x00\x00\x00\x00\x00\x00\x00\x00\x00"

This can be converted to a bit string via String#unpack:

rectangle.to_binary_s.unpack('b*')
#=> ["00110000000000000000000000000000000000000000000000000000000000000000000000000000"]

Or to a bit array via:

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]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top