From: Joel VanderWerf Date: 2009-07-01T01:22:17+09:00 Subject: Re: Question on networking with custom binary interface. Greg Chambers wrote: > Joel VanderWerf wrote: >> Greg Chambers wrote: >>> Any advice for doing this type of binary IO? >> Array#pack, String#unpack are your friends. > > I am looking at the documentation of these methods and this covers a LOT > of what I need to do, but I am worried in a couple areas. For example, > part of the binary string I will be getting will contain an eight byte > unsigned long long. How should I approach custom byte structures like > this? Ok, Array#pack, String#unpack are your _relatives_. BitStruct is your _friend_. require 'bit-struct' class MyPacket < BitStruct unsigned :x, 8*8, "The x field", :endian => :network # :network is the default, and it's the same as :big unsigned :y, 8*8, "The y field", :endian => :little end pkt = MyPacket.new pkt.x = 59843759843759843 pkt.y = 59843759843759843 p pkt.x # 59843759843759843 p pkt.y # 59843759843759843 p pkt.inspect # "#" p pkt.to_s.inspect # "\"\\000\\324\\233\\225\\037\\202\\326\\343\\343\\326\\202\\037\\225\\233\\324\\000\"" puts pkt.inspect_detailed # MyPacket: # The x field = 59843759843759843 # The y field = 59843759843759843 puts MyPacket.describe # byte: type name [size] description # ---------------------------------------------------------------------- # @0: unsigned x [ 8B] The x field # @8: unsigned y [ 8B] The y field -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407