First I checked Wikipedia to make sure I understood the operation. It looks like you are losing your carry. In addition, I added a testing class to make sure I get the right answers. I was not sure if you wanted to keep the bits portable or not, so I commented out the code to truncate the result. Hope this helps!
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, answer assert_equal 0, carry end def test_second_carry result = 5.rotate_left(4,4) answer = result & 15 carry = ( result & 16 ) >> 4 assert_equal 2, answer assert_equal 1, carry end def test_full_rotation result = 5.rotate_left(5,4) answer = result & 15 carry = ( result & 16 ) >> 4 assert_equal 5, answer assert_equal 0, carry end end end
source share