elgoog
elgoog

Reputation: 77

How can I read a slice with other size in crystal?

I would like to read 1st 2bytes of a file as “unsigned int”.

I checked the thread "Crystal reading x bytes from file" and I could get 1st 2bytes with following code.

File.open("./test/test_data") do |io|
  buffer = Slice(UInt8).new(2)
  bytes_read = io.read(buffer)
  buffer = buffer[0, bytes_read]
  pp buffer
end

However, this code returns "2 UInt8"

$ crystal test2.cr
buffer # => Slice[0, 6]

How can I read this "2 UInt8" as "1 UInt16"?

Upvotes: 2

Views: 253

Answers (1)

Oleh Prypin
Oleh Prypin

Reputation: 34116

File.open("test/test_data") do |io|
  p UInt16.from_io(io, IO::ByteFormat::LittleEndian)
end

Int.from_io

Upvotes: 4

Related Questions