I would like to cast unsigned int (32bit) A to unsigned short int (16bit) B in a following way:
- if A <= 2^16-1 then B=A
- if A > 2^16-1 then B=2^16-1
In other words to cast A but if it is > of maximum allowed value for 16bit to set it as max value.
How can this be achieved with bit operations or other non branching method?
Find minimum of two integers without branching:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
Just to kick things off, here’s a brain-dead benchmark. I’m trying to get a 50/50 mix of large and small values “at random”:
On my compiler (gcc 4.3.4 on cygwin with -O3),
NORMALwins, followed byRUSLIK, thenBITHACK, respectively 0.3, 0.5 and 0.9 seconds slower than the empty loop. Really this benchmark means nothing, I haven’t even checked the emitted code to see whether the compiler’s smart enough to outwit me somewhere. But I like ruslik’s anyway.