If you are Java/Javascript/AS3 developer, you know what the >>> operator does.
It is called unsigned right shift, or logical right shift. Check the definition in wikipedia.
However, C# and C++ don’t have such operator for signed integers, though it is available for unsigned integers. Here is one of my implementation. Hope it helps if you looking for such code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
int unsignedRightShift(int num, int offset){ // 1. Convention to check negative offset // 2. Check num == 0 to avoid different representation of positive/negative zero if (offset < 0 || num == 0) { return 0; } else if (offset == 0) { return num; } else if (num < 0) { // Don't use 0x80000000, because some platform (.NET) treat it as long but not integer. // Use left shift to get the desired bit pattern. This number can be cached for performance return ((num >> 1) ^ (1 << 31)) >> (offset - 1); } else { return num >> offset; } } |