简体   繁体   中英

It is possible to get a binary array from a BinData::Record instance?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM