0

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 writing the above byte array to the serial port. Now I am trying to do the same in ruby.

3
  • 1
    What is it supposed to do? Did you try ['B', [0x00, 0x04, 0xcc, 0x50]].to_s? Commented Jul 18, 2011 at 6:36
  • I am trying to send an array of 4 bytes to the serial port Commented Jul 18, 2011 at 6:41
  • You really need to beef up the question or else nobody will be able to help you. Commented Jul 18, 2011 at 6:42

3 Answers 3

6

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks mu, It helped me solved the issue. I have green signal and have given an upvote
@Billy: The reverse is String#unpack in case you need to read some bytes from the port and turn them into useful numbers and the like.
Hi mu, thanks again... The above comment helped me to read the data from the port.
1

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

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.