2011-09-09 102 views
2

我試圖將我的一些Java代碼轉換爲(J)Ruby,並且由於缺乏按位運算的經驗,我遇到了一個我似乎無法完成的問題由我自己解決。Ruby無符號右移運算符

簡而言之,我不知道如何將這段Java代碼轉換爲Ruby,因爲Ruby似乎沒有無符號的右移運算符(>>>)。

private static short flipEndian(short signedShort) { 
    int input = signedShort & 0xFFFF; 
    return (short) (input << 8 | (input & 0xFF00) >>> 8); 
} 

def self.flip_endian(signed_short) 
    input = signed_short & 0xFFFF 
    input << 8 | (input & 0xFF00) >> 8 
end 
+0

這可有助於:http://stackoverflow.com/questions/5284369/ruby-return -byte-array-containing-twos-complement-representation-of-bignum-fix –

+0

如果你可以使用原始字節代替,那麼['Array#pack'](http://www.ruby-doc.org /core/classes/Array.html#M000206)。 –

回答

0

這將交換前2個字節和切斷一個整數的所有較高位:

def self.flip_endian(input) 
    input << 8 & 0xFF00 | input >> 8 & 0xFF 
end