2013-08-20 13 views
0

我使用紅寶石寶石Bindata,使用下面的代碼:從BinData :: Record實例中獲取二進制數組是可能的嗎?

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, ...]數組與對象內的所有字段的二進制表示獲得?

回答

2

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] 
+0

謝謝斯特凡,爽又快! – jfcalvo

相關問題