On 03/11/11 13:42, Dan Simpson wrote:
There is probably a more elegant solution, but you can use bit shifts
and masks

I think mask, shift, and collect is about it.

Here's another version that doesn't require you specify the number of bytes:

class Fixnum
  def to_byte_array
    x      = self
    result = []
    until x == 0
      result = [x & 0xff] + result
      x      = x >> 8
    end
    result
  end
end

require 'pp'
pp 65537.to_byte_array
pp 35.to_byte_array

--Steve

--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby

Reply via email to