ruby-nuby bytes question

  • Thread starter steven.shingler
  • Start date
S

steven.shingler

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 :)

Thanks
Steven
 
R

Robert Klemme

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 :)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top