Skip to content

Commit 5aa0d1e

Browse files
authored
Merge pull request #461 from niteria/msvc2017-ffs-off-by-one
Fix off-by-one in MSCVs version of ffs(int x)
2 parents 678a241 + fb25877 commit 5aa0d1e

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/be_mem.c

+6-1
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,15 @@
4040
#elif defined(_MSC_VER)
4141
#define popcount(v) __popcnt(v)
4242

43+
// Find a free slot in the space bitmask
44+
// Find the least significant 1-bit in x and return its 1-based index.
4345
static int ffs(unsigned x)
4446
{
4547
unsigned long i;
46-
return _BitScanForward(&i, x) ? i : 0;
48+
// NOTE: _BitScanForward is 0-based, see:
49+
// https://learn.microsoft.com/en-us/cpp/intrinsics/bitscanforward-bitscanforward64?view=msvc-170
50+
// _BitScanForward(&index, 12) populates index with 2
51+
return _BitScanForward(&i, x) ? i + 1 : 0;
4752
}
4853
#else
4954
/* https://github.com/hcs0/Hackers-Delight/blob/master/pop.c.txt - count number of 1-bits */

0 commit comments

Comments
 (0)