GCC, ASM, BitScan
Posted: 31 Aug 2014, 10:39
- Code: Select all
/***
Serg Nifont
GCC, Bit Scan forward and rewers with ASM inline
(32 bit code)
Idea get from ... sorry
***/
#include <stdio.h>
#include <stdlib.h>
typedef unsigned U32;
// i - in
// r - result
#define bsf(r, i) \
do { \
asm("bsf %1, %0" : "=r" (r) : "rm" (i)); \
} while(0)
U32 BSF32(U32 r){
asm("bsf %1, %0" : "=r" (r) : "rm" (r)); \
return r;
}
U32 BSR32(U32 r){
asm("bsr %1, %0" : "=r" (r) : "rm" (r)); \
return r;
}
#define GETFIRST(w) (U32)((w&0xFFFFFFFF) ? BSF32(w&0xFFFFFFFF) : (BSF32(w>>32)+32))
#define GETLAST(w) (U32)((w>>32) ? BSR32(w>>32)+32 : BSR32(w&0xFFFFFFFF))
int main(int argc, char **argv) {
U32 first,last,k;
unsigned long long i;
for(k = 0; k < 64; k++)
{
i = (1ULL<<k);// | (1ULL<<(63-k));
//bsf(bit_n, i);
first = GETFIRST(i);
last = GETLAST(i);
printf("%u-%d-%d; ", k, first, last);
}
puts("");
return 0;
}