X-Git-Url: https://git.friedersdorff.com/?a=blobdiff_plain;f=common%2Futil.c;h=ff1926d7d14e0c58cb35249ebd5f03b430b7cfbf;hb=083c75816fbad6bcbbc268eb77e5011d2d16656b;hp=36afdd44706670bf0e4ec79b86d7573703f4b692;hpb=62d1ebb91c7b381ce3d88aad9ee0b03bea9fce26;p=max%2Ftmk_keyboard.git diff --git a/common/util.c b/common/util.c index 36afdd44..ff1926d7 100644 --- a/common/util.c +++ b/common/util.c @@ -17,19 +17,42 @@ along with this program. If not, see . #include "util.h" -// bit population -int bitpop(uint8_t bits) +// bit population - return number of on-bit +uint8_t bitpop(uint8_t bits) { - int c; + uint8_t c; for (c = 0; bits; c++) - bits &= bits -1; + bits &= bits - 1; return c; +/* + const uint8_t bit_count[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; + return bit_count[bits>>4] + bit_count[bits&0x0F] +*/ +} + +uint8_t bitpop16(uint16_t bits) +{ + uint8_t c; + for (c = 0; bits; c++) + bits &= bits - 1; + return c; +} + +// most significant on-bit - return highest location of on-bit +// NOTE: return 0 when bit0 is on or all bits are off +uint8_t biton(uint8_t bits) +{ + uint8_t n = 0; + if (bits >> 4) { bits >>= 4; n += 4;} + if (bits >> 2) { bits >>= 2; n += 2;} + if (bits >> 1) { bits >>= 1; n += 1;} + return n; } -// most significant on-bit -int biton(uint8_t bits) +uint8_t biton16(uint16_t bits) { - int n = 0; + uint8_t n = 0; + if (bits >> 8) { bits >>= 8; n += 8;} if (bits >> 4) { bits >>= 4; n += 4;} if (bits >> 2) { bits >>= 2; n += 2;} if (bits >> 1) { bits >>= 1; n += 1;}