开发者

Ruby equivalent for python array

I need a ruby equivalent for the following python code

import array
my_array = array.array('B', [0x00, 0x04, 0xcc, 0x50]).tostring()

UPDATE: I am trying to write 4 bytes to the serial port using ruby-serialport gem.

I was able to make it work in python by wri开发者_开发百科ting the above byte array to the serial port. Now I am trying to do the same in ruby.


Are you looking for Array#pack?

byte_string = [0x00, 0x04, 0xCC, 0x50].pack('C*')

From the fine manual:

arr.pack ( aTemplateString ) → aBinaryString
Packs the contents of arr into a binary sequence according to the directives in aTemplateString.

The C template is for unsigned eight bit integers (i.e. single bytes) and the * just means "use the preceding template for the rest of the elements in the array".


Seems like you want to get the following string: \x00\x04\xccP. You can simply write "\x00\x04\xcc\x50"


You can put bytes, which are given in hexadecimal, directly into your string. Below piece is valid for both Python and Ruby.

"\x00\x04\xcc\x50"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜