# 通过Ruby中的left进行左旋转

Ruby中实现SHA1,为了做到这一点,我需要通过carry执行左旋转.我写的代码似乎可以用于1次旋转,但是除了测试失败之外,还有谁知道为什么？

``````class Integer
def rotate_left(count, size)
temp = self

count.times do
first_bit = (self & 2 ** size)[size]
temp = temp << 1
temp = temp ^ first_bit
temp = temp ^ (2 ** (size + 1))
end

return temp
end
end
``````

Wikipedia以确保我理解了操作.看起来你好像丢失了随身携带物.另外,我添加了测试类,以确保我得到了正确的答案.我不确定你是否想要保留所携带的位,所以我注释掉了截断结果的代码.希望这可以帮助！

``````class Integer
def rotate_left(count, size)
temp = self
carry = 0

count.times do
temp = temp << 1
temp = temp | carry
carry = (temp >> size) & 1
end

return temp # & (( 1 << size ) - 1)
end

end

if __FILE__ == \$0 then

require 'test/unit'

class TestRotateLeft < Test::Unit::TestCase
def test_no_rotation
result = 5.rotate_left(0,4)
carry = ( result & 16 ) >> 4
assert_equal 5, result
assert_equal 0, carry
end

def test_one_rotation
result = 5.rotate_left(1,4)
carry = ( result & 16 ) >> 4
assert_equal 0, carry
end

def test_first_carry
result = 5.rotate_left(2,4)
carry = ( result & 16 ) >> 4
assert_equal 1, carry
end

def test_shift_from_carry
result = 5.rotate_left(3,4)
carry = ( result & 16 ) >> 4
assert_equal 0, carry
end

def test_second_carry
result = 5.rotate_left(4,4)
carry = ( result & 16 ) >> 4
assert_equal 1, carry
end

def test_full_rotation
result = 5.rotate_left(5,4)