If this can be done in x86 assembly, check out the BSR instruction...