2

我想将文件的第一个 2 字节读取为“无符号整数”。

我检查了线程“ Crystal reading x bytes from file ”,我可以使用以下代码获得第一个 2bytes。

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

但是,此代码返回“2 UInt8”

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

如何将这个“2 UInt8”读为“1 UInt16”?

4

1 回答 1

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

int.from_io

于 2016-08-16T13:48:31.947 回答