From: Mental Guy Date: 2008-01-23T06:22:02+09:00 Subject: Re: Circular shift Zangief Ief wrote: > I would like to write a simple implementation of *circular shift* > (http://en.wikipedia.org/wiki/Circular_shift). Thank you all for any > ideas :) The silly things people are doing to avoid using bitwise operations notwithstanding, there's really only one way to do it. I'll break it down into individual pieces so you can see how it works: def bitmask(bits) ( 1 << bits ) - 1 end def shift_left_width(value, register_width, bits) ( value << bits ) & bitmask(width) end def circular_shift_right(value, register_width, bits) remaining_bits = register_width - bits top = shift_left_width(value, register_width, remaining_bits) bottom = value >> bits top | bottom end def circular_shift_left(value, register_width, bits) remaining_bits = register_width - bits top = shift_left_width(value, register_width, bits) bottom = value >> remaining_bits top | bottom end (If you know the width of the shift register or the number of bits to shift in advance, you can simplify the math.) -mental -- Posted via http://www.ruby-forum.com/.