Wednesday, 17 March 2010

Right Shift for the win

I have learned something new today.

Something that had been a "don't know, won't assume" has finally filtered into a fact. Right shift operator maintains the highest bit.
I didn't know if this was true, or if it was somehow costly, but I remember it not being true too. I now also remember there being a difference between arithmetic right shift and just plain right shift. Now the important thing here is, if you can provide a last bit, you can provide a mask.

i.e., any negative number right shifted by 31 (while identified as a signed int of 32 bits), is -1, or, the all inclusive mask. Any positive number, right shifted by 31 is 0, or, the all exclusive mask.

Now, apply that logic to branches and you get a good general branchless technique for value manipulation. Remember, most significant bit is maintained when you use signed types, don't go using unsigned ints.

Have fun!
Post a Comment