bindataで バイナリデータを 楽に扱う

Post on 22-Jan-2018

500 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

BinDataでバイナリデータを

楽に扱うshuzo_kino

お品書き

1. 自己紹介

2. Bindataとは?

3. Bindataの基礎構文

4. Bindataの強み

5. さいごに

自己紹介

Twitter: @shuzo_kino

ゆるふわ零細事業主(情報系)

電気通信大学を8年かけて卒業

自己紹介:個人技術ブログ

ByeByeMoore

現在、連続更新記録356日

……後少しで一年毎日更新

http://shuzo-kino.hateblo.jp/

お品書き

1. 自己紹介

2. Bindataとは?

3. Bindataの基礎構文

4. Bindataの強み

5. さいごに

シリアルからデータを読むと、

こんな文字列がきます。

"~ \u0004 abcd @"

"~ \u0004 abcd @"

開始文字

データ長

データ本体

終了文字

さて、これを

どう分けましょう?

間に合わせで書くと、

こんな感じ?

"~\u0004abcd@".unpack("C*").map.with_index{|x,idx| (2..5).include?(idx) ? x.chr : x}

#=> [126, 4, "a", "b", "c", "d", 64]

いくらでも複雑になりそう……

こんな時は、

BinDataを

使うと楽です

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len string :str, :read_length => :len uint8 :tailend

p SampleBase.read("~\u0004abcd@")

こんな感じで格納されます

{:head=>126, :len=>4, :str=>"abcd", :tail=>64}

読み込みも、

通常のRubyな感覚で大丈夫。

アレコレデータを整形する際も

苦労しません。

a = SampleBase.read("~\u0004abcd@")puts a.str[0] + a.str[-1] #=> “ad”

お品書き

1. 自己紹介

2. Bindataとは?

3. Bindataの基礎構文

4. Bindataの強み

5. さいごに

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len string :str, :read_length => :len uint8 :tailend

p SampleBase.read("~\u0004abcd@")

Gem “bindata”を導入します。

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len string :str, :read_length => :len uint8 :tailend

p SampleBase.read("~\u0004abcd@")

普通に使う分には、BinData::Recordを継承するだけで十分実用に足ります

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len string :str, :read_length => :len uint8 :tailend

p SampleBase.read("~\u0004abcd@")

エンディアンの指定も可能です。要素毎の設定も容易。

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len string :str, :read_length => :len uint8 :tailend

p SampleBase.read("~\u0004abcd@")

ビット列と文字が混在可能!

お品書き

1. 自己紹介

2. Bindataとは?

3. Bindataの基礎構文

4. Bindataの強み

5. さいごに

急で悪いんだけどさー

センサの種類が

変わったんだよね〜

具体的には、こうなった

"~ \u0004 \u0042\u0011\u0012\u0000 @"

ACIIがビット列になった(怒

大丈夫。

BinDataならスグです

require 'bindata'

class SampleBase < BinData::Record endian :big uint8 :head uint8 :len array :body, :type => :uint8, :initial_length => :len uint8 :tailend

p SampleBase.read("~\u0004\u0042\u0011\u0012\u0000 @")

型を変換するだけ

読み込みも引き続き問題なし。

a = SampleBase.read("~\u0004\u0042\u0011\u0012\u0000@")puts a.body[0] + a.body[-1] #=> 66

\uは16進数表記なので 0x42 + 0x12 = 0x54 = 66

お品書き

1. 自己紹介

2. Bindataとは?

3. Bindataの基礎構文

4. Bindataの強み

5. さいごに

BinDataを使えば、

コロコロ変わるパケットにも容

易に対処可能!

ガンガン使ってきましょう!

top related