I'm trying to return a byte array containing the two's-complement representation of a Bignum or Fixnum (in Ruby). There's a method in Java that does exactly that - Docs: Java toByteArray() method, Code for it: https://gist.github.com/867409
My requirements are the same as the Java method (taken from the Java page): The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8))
.
Ruby doesn't have the >>>
operator which (I think) is why I'm having so many issues getting this concept converted to Ruby.
Adding some not-working code:
def to_byte_array(num)
result = []
until num == 0
result = [num & 0xff] + result
num = num >> 8
end
result
end