我正在测试有关字节或切片的序列化,只是学习和尝试。我想在单个10字节字段中绑定3个参数,但我现在不知道如何将它们连接到水晶中,也不知道是否可能。我知道我可以通过创建数组或元组来实现这一点,但我想尝试是否可以将参数混合到一个缓冲区中。
例如,我需要一个自描述的二进制记录ID混合3个参数:
类型(UInt8) \x{e76f}类别(UInt8) =微秒(UInt64) =总共80位- 10字节
type = 1_u8 # 1 byte
categ = 4_u8 # 1 byte
usec = 1527987703211000_u64 # 8 bytes (Epoch)如何将所有这些变量连接到一个连续的10字节缓冲区中?
我想按索引检索数据,例如:
type = buff[0,1]
categ = buff[1,1]
usec = buff[2,8].to_u64 # (Actually not possible)发布于 2018-06-03 08:20:39
typ = 1_u8 # 1 byte
categ = 4_u8 # 1 byte
usec = 1527987703211000_u64 # 8 bytes (Epoch)
FORMAT = IO::ByteFormat::LittleEndian
io = IO::Memory.new(10) # Specifying the capacity is optional
io.write_bytes(typ, FORMAT) # Specifying the format is optional
io.write_bytes(categ, FORMAT)
io.write_bytes(usec, FORMAT)
buf = io.to_slice
puts buf
# --------
io2 = IO::Memory.new(buf)
typ2 = io2.read_bytes(UInt8, FORMAT)
categ2 = io2.read_bytes(UInt8, FORMAT)
usec2 = io2.read_bytes(UInt64, FORMAT)
pp typ2, categ2, usec2Bytes[1, 4, 248, 99, 69, 92, 178, 109, 5, 0]
typ2 # => 1_u8
categ2 # => 4_u8
usec2 # => 1527987703211000_u64这展示了一个为您的用例量身定做的示例,但是IO::Memory一般应该用于“串联字节”--只需写到它。
发布于 2020-01-23 09:53:30
这不是对您问题的回答,但当我试图连接实际的Bytes[]时,我一直在这里结束。Oleh的答案仍然适用,但我在这里尝试给出一种更通用的方法:
# some bytes a
a = Bytes[131, 4, 254, 47]
# some other bytes b
b = Bytes[97, 98, 99]
# new buffer of sizes a and b
c = IO::Memory.new a.bytesize + b.bytesize
# without knowing the size of the slice, we just write byte by byte
a.each do |v|
# each byte can be represented by an u8
c.write_bytes UInt8.new v
end
# same for b
b.each do |v|
c.write_bytes UInt8.new v
end
# here you have your new bytes slice
c = c.to_slice
# => Bytes[131, 4, 254, 47, 97, 98, 99]注意,这只适用于默认的IO::ByteFormat::LittleEndian,因此在示例中省略。
https://stackoverflow.com/questions/50662604
复制相似问题