tags:

views:

25

answers:

1

I have a column named a, and a column named b.

I want to fill with an UPDATE ... SET b = ... query the b column, so that it contains the first bit that a has set to 1. Okay, you probably didn't understand, it's much easier to understand with an example:

a = 2508 = 0x9CC = 0100111001100  
b = 4    = 0x4   = 0000000000100

a = 2080 = 0x820 = 0100000100000  
b = 32   = 0x20  = 0000000100000

Is there a way to do this in pure SQL?

+2  A: 

This should do it:

update your_table
set b = if(a > 0,pow(2,instr(reverse(bin(a)),'1')-1),0);
Ike Walker
And what if the most-significant bit is set? I assume we can have negatives, too.
Justin K
@Justin: The most significant bit is treated like all other bits. If `a` is less than or equal to 0, then I set `b` to 0.
Ike Walker
Yeah, but if a is negative, the first bit must be set, so b will not be 0. It would instead be INT_MIN, right? Unless I'm misunderstanding something...
Justin K
@Justin: I'll leave it to the OP to decide how to handle negative values of `a` (and 0). That wasn't covered by the original examples. My code will work for those examples. For all I know the data type of `a` is unsigned, in which case this discussion is irrelevant.
Ike Walker
I don't think it is unsigned, but regardless it's a bitmask in which only 6 bits are currently used and it won't ever reach 32, so this answer worked great. Thanks!
Andreas Bonini