Fastest way to enumerate through turned on bits of an integer

后端 未结 8 1177
暗喜
暗喜 2021-02-06 08:22

What\'s the fastest way to enumerate through an integer and return the exponent of each bit that is turned on? Have seen an example using << and another u

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 08:45

    The fastest way? Lookup tables are almost always the fastest way. Build an int[][] array with four billion entries, one for each int, containing an array of the numbers you want. Initializing the table will take some time, of course but the lookups will be incredibly fast.

    I note that you have not said what "fastest" means with sufficient precision for anyone to actually answer the question. Does it mean fastest amortized time including startup time, or marginal lookup time assuming that startup costs can be neglected? My solution sketch assumes the latter.

    Obviously a 32 bit machine with 2 billion bytes of address space will not have enough address space to store thirty billion bytes of arrays. Get yourself a 64 bit machine. You'll need at least that much physical memory installed as well if you want it to be fast -- the paging is going to kill you otherwise.

    I sure hope the couple of nanoseconds you save on every lookup are worth buying all that extra hardware. Or maybe you don't actually want the fastest way?

    :-)

提交回复
热议问题