Mysql – Calculate MSB on MySQL

MySQL

Suppose I have Table A

|-10|
|-1 |
|0  |
|1  |
|10 |
|100|

and take the most significant bit position of each value and import it into Table B, like so:

|-4|
|-1|
|0 |
|1 |
|4 |
|7 |

How do we do it efficiently? Is there a user-defined function that mimics the behavior of __builtin_clz as with GCC?

UPDATE: Added example for zero and negative values.

Best Answer

Like this?

 INSERT INTO b SELECT FLOOR(LOG2(Col1)) + 1 FROM a;