I’d like a shortcut for the following little function, where
performance is very important (the function is called more than 10.000.000 times):
inline int len(uint32 val)
{
if(val <= 0x000000ff) return 1;
if(val <= 0x0000ffff) return 2;
if(val <= 0x00ffffff) return 3;
return 4;
}
Does anyone have any idea… a cool bitoperation trick?
Thanks for your help in advance!
How about this one?
Removing the
inlinekeyword,g++ -O2compiles this to the following branchless code:If you don’t mind machine-specific solutions, you can use the
bsrinstruction which searches for the first 1 bit. Then you simply divide by 8 to convert bits to bytes and add 1 to shift the range 0..3 to 1..4:Note that I am not an inline assembly god, so maybe there’s a better to solution to access
valinstead of addressing the stack explicitly. But you should get the basic idea.The GNU compiler also has an interesting built-in function called
__builtin_clz:This looks much better than the inline assembly version to me 🙂