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:
The end condition is a bit tricky. Here it goes:
def to_byte_array(num)
result = []
begin
result << (num & 0xff)
num >>= 8
end until (num == 0 || num == -1) && (result.last[7] == num[7])
result.reverse
end
p [0, 1, 255, 256, -1, -128, -256].map{|i| to_byte_array(i)}
# => [[0], [1], [0, 255], [1, 0], [255], [128], [255, 0]]