qpi
qpi

Reputation: 209

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?

Upvotes: 0

Views: 143

Answers (1)

Stephie
Stephie

Reputation: 3175

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.

Upvotes: 6

Related Questions