Ruby - Return byte array containing two's comp

2019-02-19 02:39发布

问题:

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

回答1:

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]]