kbit.h 1.1 KB

123456789101112131415161718192021222324252627282930
  1. #ifndef KBIT_H
  2. #define KBIT_H
  3. #include <stdint.h>
  4. static inline uint64_t kbi_popcount64(uint64_t y) // standard popcount; from wikipedia
  5. {
  6. y -= ((y >> 1) & 0x5555555555555555ull);
  7. y = (y & 0x3333333333333333ull) + (y >> 2 & 0x3333333333333333ull);
  8. return ((y + (y >> 4)) & 0xf0f0f0f0f0f0f0full) * 0x101010101010101ull >> 56;
  9. }
  10. static inline uint64_t kbi_DNAcount64(uint64_t y, int c) // count #A/C/G/T from a 2-bit encoded integer; from BWA
  11. {
  12. // reduce nucleotide counting to bits counting
  13. y = ((c&2)? y : ~y) >> 1 & ((c&1)? y : ~y) & 0x5555555555555555ull;
  14. // count the number of 1s in y
  15. y = (y & 0x3333333333333333ull) + (y >> 2 & 0x3333333333333333ull);
  16. return ((y + (y >> 4)) & 0xf0f0f0f0f0f0f0full) * 0x101010101010101ull >> 56;
  17. }
  18. #ifndef kroundup32 // round a 32-bit integer to the next closet integer; from "bit twiddling hacks"
  19. #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
  20. #endif
  21. #ifndef kbi_swap
  22. #define kbi_swap(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) // from "bit twiddling hacks"
  23. #endif
  24. #endif