Forum: Ruby ruby-nuby bytes question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9e43ca413ca99adad22a9442c56ebdf6?d=identicon&s=25 unknown (Guest)
on 2006-02-07 12:14
(Received via mailing list)
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
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-02-07 12:30
(Received via mailing list)
steven.shingler@virgin.net 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 :)

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
9e43ca413ca99adad22a9442c56ebdf6?d=identicon&s=25 unknown (Guest)
on 2006-02-07 12:54
(Received via mailing list)
super!
thanks robert :)
This topic is locked and can not be replied to.