Search code examples
crystal-lang

How do I replicate this specific pack example in crystal?


Ruby code sample:

"\u0000\u0000\u0000\u0002".unpack('N')[0]  #=> 2 

How can I do this with crystal language?


Solution

  • You can use the IO#read_bytes method to read integers from many places. For example

    io = IO::Memory.new("\u0000\u0000\u0000\u0002")
    io.read_bytes(UInt32, format: IO::ByteFormat::NetworkEndian) # => 2
    

    I would advise against using strings to store binary data though, reading directly from IO, or storing using the Bytes type is much more idiomatic Crystal.