There is probably a more elegant solution, but you can use bit shifts and
masks

I hacked this little snippet together

require "pp"

def to_byte_array num, bytes
  (bytes - 1).downto(0).collect { |byte|
    ((num >> (byte * 8)) & 0xFF)
  }
end

pp to_byte_array(65537, 4)
pp to_byte_array(0xF1E1D1C1, 4).collect { |i| "%02x" % i }

--Dan

On Fri, Mar 11, 2011 at 1:20 PM, James Miller <[email protected]> wrote:

> Hey Guys,
>
> Got a weird one for you all -- anyone know how to convert a Fixnum/Bignum
> into a two's-complement byte array (in Ruby)?
>
> Examples of what I'm looking to do using a non-existent
> Fixnum#to_byte_array method:
>
> 65537.to_byte_array
> # => [0,1,0,1]
>
> 35.to_byte_array
> # => [35, 0]
>
> Java equivalent:
> http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html#toByteArray()
>
> Thanks,
> James
>
> --
> SD Ruby mailing list
> [email protected]
> http://groups.google.com/group/sdruby

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

Reply via email to