加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过Ruby中的left进行左旋转

发布时间:2020-12-17 02:10:55 所属栏目:百科 来源:网络整理
导读:我正在尝试在 Ruby中实现SHA1,为了做到这一点,我需要通过carry执行左旋转.我写的代码似乎可以用于1次旋转,但是除了测试失败之外,还有谁知道为什么? class Integer def rotate_left(count,size) temp = self count.times do first_bit = (self 2 ** size)[si
我正在尝试在 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)
            answer = result & 15
            carry = ( result & 16 ) >> 4
            assert_equal 5,result
            assert_equal 0,carry
        end

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

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

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

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

        def test_full_rotation
            result = 5.rotate_left(5,carry
        end

    end

end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读