好的,我的最后一个问题-假设我具有以下数据结构:
byte length
byte message_code
byte[] payload
写入管道时,数据的每一位都必须具有正确的数据类型,这一点非常重要;如何确保我的数据数组(在Ruby中看起来像这样):
data = [ 15, 0, .... ] # the ... indicates the payload
是写为单个字节-即15写为一个字节,而不是两个字符(即“ 1”和“ 5”)?
目前,我的数据正在转换为字符串,然后写入,这意味着15不会写为15,而是写为“ 1”和“ 5”的单个字符。这意味着在管道中,它的显示方式如下:
"1, 5, 0, 4, 1, 2, 1, 0, 4" (notice that the 1 is an individual character instead of being a part of 15)
代替
150412104 (etc)
感谢Uri Agassi,我完成的代码如下所示:
data = [ 15, # message code + payload size
0, # message code
4, # protocol version
12, # size of string
]
data.concat('hello, world'.bytes.to_a)
p data
packed_data = data.pack 'c*' # Convert the data into a string containing 8-bit unsigned characters
借助此答案-使用Array#pack和String#unpack在二进制表示形式之间进行转换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句