What is the fastest way to return the positions of all set bits in a 64-bit integer?

后端 未结 10 1898
北荒
北荒 2020-12-13 04:05

I need a fast way to get the position of all one bits in a 64-bit integer. For example, given x = 123703, I\'d like to fill an array idx[] = {0, 1, 2, 4,

10条回答
  •  春和景丽
    2020-12-13 04:44

    If I take "I need a fast way to get the position of all one bits in a 64-bit integer" literally...

    I realise this is a few weeks old, however and out of curiosity, I remember way back in my assembly days with the CBM64 and Amiga using an arithmetic shift and then examining the carry flag - if it's set then the shifted bit was 1, if clear then it's zero

    e.g. for an arithmetic shift left (examining from bit 64 to bit 0)....

    pseudo code (ignore instruction mix etc errors and oversimplification...been a while):
    
        move #64+1, counter
        loop. ASL 64bitinteger       
        BCS carryset
        decctr. dec counter
        bne loop
        exit
    
        carryset. 
        //store #counter-1 (i.e. bit position) in datastruct indexed by counter
        jmp decctr
    

    ...I hope you get the idea.

    I've not used assembly since then but I'm wondering if we could use some C++ in-line assembly similar to the above to do something similar here. We could do the whole conversion in assembly (very few lines of code), building up an appropriate data structure. C++ could simply examine the answer.

    If this is possible then I'd imagine it to be pretty fast.

提交回复
热议问题