| 1 | #include <prim/seadBitFlag.h> |
|---|---|
| 2 | |
| 3 | namespace sead |
| 4 | { |
| 5 | int BitFlagUtil::countOnBit(u32 x) |
| 6 | { |
| 7 | x = x - ((x >> 1) & 0x55555555); |
| 8 | x = (x & 0x33333333) + ((x >> 2) & 0x33333333); |
| 9 | x = (x + (x >> 4)) & 0x0F0F0F0F; |
| 10 | x += (x >> 8); |
| 11 | x += (x >> 16); |
| 12 | return x & 0x3f; |
| 13 | } |
| 14 | |
| 15 | int BitFlagUtil::countRightOnBit(u32 x, int bit) |
| 16 | { |
| 17 | SEAD_ASSERT(static_cast<u32>(bit) < sizeof(u32) * 8); |
| 18 | const u32 mask = ((1u << bit) - 1) | (1u << bit); |
| 19 | return countOnBit(x: x & mask); |
| 20 | } |
| 21 | |
| 22 | int BitFlagUtil::findOnBitFromRight(u32 x, int num) |
| 23 | { |
| 24 | SEAD_ASSERT(num > 0); |
| 25 | if (!x) |
| 26 | return -1; |
| 27 | |
| 28 | while (--num > 0) |
| 29 | { |
| 30 | x &= x - 1; |
| 31 | if (!x) |
| 32 | return -1; |
| 33 | } |
| 34 | return countContinuousOffBitFromRight(x); |
| 35 | } |
| 36 | |
| 37 | int BitFlagUtil::countRightOnBit64(u64 x, int bit) |
| 38 | { |
| 39 | SEAD_ASSERT(static_cast<u64>(bit) < sizeof(u64) * 8); |
| 40 | const u64 mask = ((1ull << bit) - 1) | (1ull << bit); |
| 41 | return countOnBit64(x: x & mask); |
| 42 | } |
| 43 | |
| 44 | int BitFlagUtil::findOnBitFromRight64(u64 x, int num) |
| 45 | { |
| 46 | SEAD_ASSERT(num > 0); |
| 47 | if (!x) |
| 48 | return -1; |
| 49 | |
| 50 | while (--num > 0) |
| 51 | { |
| 52 | x &= x - 1; |
| 53 | if (!x) |
| 54 | return -1; |
| 55 | } |
| 56 | return countContinuousOffBitFromRight64(x); |
| 57 | } |
| 58 | |
| 59 | } // namespace sead |
| 60 |