1

だから私はいくつかのMongoDBプロトコルのものに取り組んでいます。すべての整数はリトルエンディアンで署名されています。Rubyの標準的な方法を使用して、整数からArray#pack必要なバイナリ文字列に変換できます。

positive_one = Array(1).pack('V')   #=> '\x01\x00\x00\x00'
negative_one = Array(-1).pack('V')  #=> '\xFF\xFF\xFF\xFF'

ただし、逆に言えば、このメソッドには、特に符号なし整数String#unpackを返すものとして文書化された「V」形式があります。

positive_one.unpack('V').first #=> 1
negative_one.unpack('V').first #=> 4294967295

符号付きリトルエンディアンのバイトオーダー用のフォーマッタはありません。ビットシフトを使ってゲームをプレイしたり、配列パッキングを使用しない独自のバイトマングリングメソッドを作成したりできると確信していますが、他の誰かがこれに遭遇して簡単な解決策を見つけたのではないかと思います。どうもありがとう。

4

4 に答える 4

2

編集あなたが最初に変換していた方向を誤解しました(コメントによると)。しかし、少し考えてみると、解決策は同じだと思います。これが更新されたメソッドです。まったく同じことを行いますが、コメントで結果を説明する必要があります。

def convertLEToNative( num )
    # Convert a given 4 byte integer from little-endian to the running
    # machine's native endianess.  The pack('V') operation takes the
    # given number and converts it to little-endian (which means that
    # if the machine is little endian, no conversion occurs).  On a
    # big-endian machine, the pack('V') will swap the bytes because
    # that's what it has to do to convert from big to little endian.  
    # Since the number is already little endian, the swap has the
    # opposite effect (converting from little-endian to big-endian), 
    # which is what we want. In both cases, the unpack('l') just 
    # produces a signed integer from those bytes, in the machine's 
    # native endianess.
    Array(num).pack('V').unpack('l')
end

おそらく最もクリーンではありませんが、これによりバイト配列が変換されます。

def convertLEBytesToNative( bytes )
    if ( [1].pack('V').unpack('l').first == 1 )
        # machine is already little endian
        bytes.unpack('l')
    else
        # machine is big endian
        convertLEToNative( Array(bytes.unpack('l')))
    end
end
于 2011-03-08T21:25:41.807 に答える
2

で解凍した後"V"、次の変換を適用できます

class Integer
  def to_signed_32bit
    if self & 0x8000_0000 == 0x8000_0000
      self - 0x1_0000_0000  
    else
      self
    end
  end
end

他のサイズの整数を扱う場合は、マジック定数0x1_0000_0000( 2**32) と0x8000_0000( ) を変更する必要があります。2**31

于 2011-03-09T19:33:36.363 に答える
1

この質問には、役立つ可能性のある符号付きから符号なしに変換する方法があります。それはまたあなたが望むことをするように見えるbindata宝石へのポインターを持っています。

BinData::Int16le.read("\000\f") # 3072

[not-quite-rightのunpackディレクティブを削除するように編集]

于 2011-03-08T17:53:36.583 に答える
1

後世のために、Paul Rubel の「古典的な方法」へのリンクを見つける前に、私が最終的に思いついた方法を次に示します。ぎこちなく、文字列操作に基づいているので、おそらく破棄しますが、うまくいくので、いつか他の理由で誰かが面白いと思うかもしれません:

# Returns an integer from the given little-endian binary string.
# @param [String] str
# @return [Fixnum]
def self.bson_to_int(str)
  bits = str.reverse.unpack('B*').first   # Get the 0s and 1s
  if bits[0] == '0'   # We're a positive number; life is easy
    bits.to_i(2)
  else                # Get the twos complement
    comp, flip = "", false
    bits.reverse.each_char do |bit|
      comp << (flip ? bit.tr('10','01') : bit)
      flip = true if !flip && bit == '1'
    end
    ("-" + comp.reverse).to_i(2)
  end
end

更新: Ken Bloom の回答の一般化された任意の長さの形式を使用した、より単純なリファクタリングを次に示します。

# Returns an integer from the given arbitrary length little-endian binary string.
# @param [String] str
# @return [Fixnum]
def self.bson_to_int(str)
  arr, bits, num = str.unpack('V*'), 0, 0
  arr.each do |int|
    num += int << bits
    bits += 32
  end
  num >= 2**(bits-1) ? num - 2**bits : num  # Convert from unsigned to signed
end
于 2011-03-09T19:59:52.757 に答える