0

Ruby code sample:

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

How can I do this with crystal language?

qpi
  • 209
  • 3
  • 7
  • See [this issue](https://github.com/crystal-lang/crystal/issues/276) on the Crystal GitHub. – Joe Clay Nov 30 '17 at 16:38
  • Possible duplicated of https://stackoverflow.com/questions/32725506/pack-the-contents-of-arr-into-a-binary-sequence-in-crystal – Vitalii Elenhaupt Nov 30 '17 at 17:46
  • I think the question is not "how do I use unpack in crystal", it's "how do I replicate this *specific* pack example in crystal", which is not a duplicate. perhaps the question could be phrased more generically though. – Stephie Nov 30 '17 at 19:32

1 Answers1

6

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.

Vitalii Elenhaupt
  • 7,146
  • 3
  • 27
  • 43
Stephie
  • 3,135
  • 17
  • 22