Equivalent of De Bruijn LSB, but for MSB

ε祈祈猫儿з 提交于 2019-12-11 05:23:37

问题


Does anyone know of an algorithm similar to De Bruijn's LSB, but for MSB? Or alternately the most efficient way of determining the MSB?

I know Log_2(Val) will do this, but I don't know if it's the most efficient method.

The reason I need it is I need to convert little-endian to big-endian. I know the standard algorithm for this. However, the input is 64 bit, but typically the numbers will be 16 or 24 bit, so swapping the whole 8 bytes around is unneeded 99.9% of the time.


回答1:


Isn't this exactly http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn ?




回答2:


If you want a fast method and are able/willing to use hardware specific instructions, you should take a look at x86 BSR (Bit Scan Reverse) or similar instruction.

Searches the source operand (second operand) for the most significant set bit (1 bit). If a most significant 1 bit is found, its bit index is stored in the destination operand (first operand).

xor edx, edx
mov eax, 0x12345678
bsr edx, eax

It should store 28 in edx (bit 28 is the MSB). edx would be unchanged if no MSB is found.



来源:https://stackoverflow.com/questions/5326186/equivalent-of-de-bruijn-lsb-but-for-msb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!