Skip to content

Instantly share code, notes, and snippets.

@fukaoi
Created October 17, 2018 01:58
Show Gist options
  • Select an option

  • Save fukaoi/d030127d0abd67e572ba6a157a29bd12 to your computer and use it in GitHub Desktop.

Select an option

Save fukaoi/d030127d0abd67e572ba6a157a29bd12 to your computer and use it in GitHub Desktop.
crystal pack and unpack
class String
def unpack(format : String) : Array
io = IO::Memory.new(self)
slice = Bytes.new(self.size)
io.read(slice)
[slice.hexstring]
end
end
class Array
def pack(format : String) : String
size = self[0].size
hex = self[0]
raise Exception.new("No match size") unless size % 2 == 0
slice = Slice(UInt8).new(size / 2)
0.step(to: size - 1, by: 2) do |i|
high_nibble = hex.to_unsafe[i].unsafe_chr.to_u8?(16)
low_nibble = hex.to_unsafe[i + 1].unsafe_chr.to_u8?(16)
raise Exception.new("No match nibble(high and low)") unless high_nibble && low_nibble
slice[i / 2] = (high_nibble << 4) | low_nibble
end
io = IO::Memory.new(size / 2)
io.write(slice)
io.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment