Ruby: Split binary data -
i want split data
chunks of let's 8154 byte:
data = zlib::deflate.deflate(some_very_long_string)
what best way that?
i tried use this:
chunks = data.scan /.{1,8154}/
...but data lost! data
had size
of 11682, when looping through every chunk , summing size
ended total size of 11677. 5 bytes lost! why?
regexps not way parse binary data. use bytes
, each_slice
operate bytes. , use pack 'c*'
convert them strings output or debug:
irb> data = file.open("sample.gif", "rb", &:read) => "gif89a\r\x00\r........." irb> data.bytes.each_slice(10){ |slice| p slice, slice.pack("c*") } [71, 73, 70, 56, 57, 97, 13, 0, 13, 0] "gif89a\r\x00\r\x00" [247, 0, 0, 0, 0, 0, 0, 0, 51, 0] "\xf7\x00\x00\x00\x00\x00\x00\x003\x00" ...........
Comments
Post a Comment