What is the fastest way to calculate the number of bits needed to store a number

前端 未结 6 1227
暗喜
暗喜 2021-01-12 02:50

I\'m trying to optimize some bit packing and unpacking routines. In order to do the packing I need to calculate the number of bits needed to store integer values. Here is th

6条回答
  •  渐次进展
    2021-01-12 03:29

    What you are trying to do is find the most significant bit. Some architectures have a special instruction just for this purpose. For those that don't, use a table lookup method.

    Create a table of 256 entries, wherein each element identifies the upper most bit.

    Either loop through each byte in the number, or use a few if-statements to break to find the highest order non-zero byte.

    I'll let you take the rest from here.

提交回复
热议问题