Circular bitwise operation - as3
I am new to the concept of Bitwise operations, and was messing around with some examples today. Everything seemed clear up until the point I tried to make a function to perform a circular bitshift on a uint
:
private function rotateLeft(value : uint, shift : int) : uint {
if ((shift &= 31) == 0)
return value;
return (value << shift) | (valu开发者_StackOverflow中文版e >> (32 - shift));
}
Any ideas why does this not work? This seems simple, but I think I am missing something obvious.
EDIT:
I was stupidly trying to shift a colour value (e.g. 0xFF0000) and expecting something along the lines of 0x0000FF, when in actual fact I was getting 0xFF000000 (which is correct, due to the length of a uint
) - the most significant bytes are for the alpha value.
1 - always keep your shift in the range => shift &= 31
2 - use an unsigned shift right (>>>
), otherwise you will have the bit sign that will propagate into your number, so for example (0x80000000 >> 16)
will be 0xffff8000
and not 0x00008000
.
function rotateLeft(value : uint, shift : int) : uint {
shift &= 31;
return (value << shift) | (value >>> (32 - shift));
}
精彩评论