Ruby-nuby bytes question

Hi all,

Iā€™d like to convert an int to a byte array in Ruby.

In C# you can do this:
byte[] b = BitConverter.GetBytes(BufferLength);

Any tips for the ruby equivalent gratefully received :slight_smile:

Thanks
Steven

[email protected] wrote:

Hi all,

Iā€™d like to convert an int to a byte array in Ruby.

In C# you can do this:
byte[] b = BitConverter.GetBytes(BufferLength);

Any tips for the ruby equivalent gratefully received :slight_smile:

You can use pack

irb(main):001:0> [5].pack ā€œi*ā€
=> ā€œ\005\000\000\000ā€
irb(main):002:0> [5].pack ā€œI*ā€
=> ā€œ\005\000\000\000ā€
irb(main):006:0> [5].pack(ā€œI*ā€).split //
=> ["\005", ā€œ\000ā€, ā€œ\000ā€, ā€œ\000ā€]

But note also that you can treat an int as a bit vector:

irb(main):003:0> 5[2]
=> 1
irb(main):004:0> 5[3]
=> 0

HTH

robert

super!
thanks robert :slight_smile: