Ruby - Return byte array containing two's complement representation of Bignum/Fixnum

后端 未结 1 892
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 02:29

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:

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 02:59

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

    0 讨论(0)
提交回复
热议问题