Hey Dan, Thanks for hacking that together -- you got me much closer, but not quite there yet. I think the problem is that it's still not two's complement: 35.to_byte_array # => [0, 0, 0, 35]
Should be (I think): # => [35, 0] For some context, you can see what I'm doing here - goal is to generate an SSH public key from an RSA private key without using ssh-keygen): https://gist.github.com/6fa8ff614cee70623a60 The results of running that (runs the tests): https://gist.github.com/cef92e26513b86144b6e The java method that I'm trying to mimic (seems the hangup is that Ruby doesn't have the triple >>> operator): https://gist.github.com/e8a8b1f99da9ebc57c2f Thanks, James On Fri, Mar 11, 2011 at 1:42 PM, Dan Simpson <[email protected]> wrote: > 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
