首页 文章

如何在Crystal中连接字节

提问于
浏览
3

我正在测试有关字节或切片的序列化,只是学习和尝试 . 我想在一个10字节的字段中绑定3个参数,但我现在不知道如何在Crystal中连接它们或者是否可能 . 我知道我可以通过创建数组或元组来实现这一点,但我想尝试是否可以将参数混合到单个缓冲区中 .

例如,我想要一个混合3个参数的自描述二进制记录ID:

输入(UInt8)|类别(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)

1 回答

  • 5
    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, usec2
    
    Bytes[1, 4, 248, 99, 69, 92, 178, 109, 5, 0]
    typ2   # => 1_u8
    categ2 # => 4_u8
    usec2  # => 1527987703211000_u64
    

    这显示了一个根据您的用例量身定制的示例,但 IO::Memory 通常应该用于"concatenating bytes" - 只需写入即可 .

相关问题