bit_util: std::bitset-based BitCount implementation
Suggestion by @lioncash.
This commit is contained in:
parent
5aa4f753b6
commit
cc3e7e71aa
1 changed files with 4 additions and 6 deletions
|
@ -6,6 +6,7 @@
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <bitset>
|
||||||
#include <climits>
|
#include <climits>
|
||||||
|
|
||||||
#include "common/assert.h"
|
#include "common/assert.h"
|
||||||
|
@ -71,12 +72,9 @@ inline T SignExtend(const T value) {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline size_t BitCount(u32 value) {
|
template <typename Integral>
|
||||||
// Portable SWAR algorithm for population count
|
inline size_t BitCount(Integral value) {
|
||||||
value = value - ((value >> 1) & 0x55555555); // Two-bit count
|
return std::bitset<BitSize<Integral>()>(value).count();
|
||||||
value = (value & 0x33333333) + ((value >> 2) & 0x33333333); // Nybble count
|
|
||||||
value = (value + (value >> 4)) & 0x0F0F0F0F; // Byte count
|
|
||||||
return ((value * 0x01010101) >> 24) & 0xFF; // Summate the byte counts
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace Common
|
} // namespace Common
|
||||||
|
|
Loading…
Reference in a new issue