Ruby-返回字节数组,其中包含Bignum/Fixnum的二进制补码表示形式 [英] Ruby - Return byte array containing two's complement representation of Bignum/Fixnum

查看:87
本文介绍了Ruby-返回字节数组,其中包含Bignum/Fixnum的二进制补码表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图返回一个字节数组,其中包含Bignum或Fixnum(在Ruby中)的二进制补码表示形式. Java中有一种方法可以做到这一点-文档: https://gist. github.com/867409

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

我的要求与Java方法相同(取自Java页面):字节数组将按big-endian字节顺序进行:最高有效字节位于第零个元素中.该数组将包含表示此BigInteger所需的最小字节数,包括至少一个符号位,即(ceil((this.bitLength() + 1)/8)).

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没有>>>运算符,(我认为)这就是为什么我遇到很多问题将这个概念转换为Ruby的原因.

Ruby doesn't have the >>> operator which (I think) is why I'm having so many issues getting this concept converted to Ruby.

添加一些无效代码:

def to_byte_array(num)
  result = []
  until num == 0
    result = [num & 0xff] + result
    num = num >> 8
  end
  result
end

推荐答案

最终条件有些棘手.在这里:

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

这篇关于Ruby-返回字节数组,其中包含Bignum/Fixnum的二进制补码表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆