How to create binary data from Ruby

Hi, I need to create binary data from Ruby to send via network some
structure like this:

  • field 1: 1 bit
  • field 2: 1 bit
  • field 3: 1 bit
  • field 4: 1 bit
  • field 5: 4 bits
  • field 6: 1 bit
  • field 7: 7 bits
  • field 8: 16 bits
    (and so on)

Which is the proer way to generate such binary data from Ruby?

Thanks a lot.

On Tue, Aug 16, 2011 at 12:34 PM, Iaki Baz C. [email protected]
wrote:

  • field 8: 16 bits
    (and so on)

Which is the proer way to generate such binary data from Ruby?

There are various ways. Off the top of my head:

  1. Use Array#pack with ‘B’ or ‘b’.

  2. Use an integer to construct the whole bit data and convert it via
    “%032b” % i.

Kind regards

robert

2011/8/16 Robert K. [email protected]:

There are various ways. Off the top of my head:

  1. Use Array#pack with ‘B’ or ‘b’.

  2. Use an integer to construct the whole bit data and convert it via
    “%032b” % i.

Thanks, using Array#pack is the way I’ve remembered (After reading your
mail) :slight_smile:

Thanks a lot.