【问题标题】:It is possible to get a binary array from a BinData::Record instance?可以从 BinData::Record 实例中获取二进制数组吗?
【发布时间】:2013-08-20 08:37:33
【问题描述】:

我正在使用 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, ...] 这样的数组,其中包含对象内所有字段的二进制表示?

【问题讨论】:

    标签: ruby binary bindata


    【解决方案1】:

    BinData::Base#to_binary_s返回“这个数据对象的字符串表示”:

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

    这可以通过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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2016-08-16
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多