utils.cc 970 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "utils.h"
  2. /* ================================================================ */
  3. /* Utility function definitions */
  4. /* ================================================================ */
  5. String myDecStr(UInt64 v, UInt32 w)
  6. {
  7. std::ostringstream o;
  8. o.width(w);
  9. o << v;
  10. String str(o.str().c_str());
  11. return str;
  12. }
  13. bool isPower2(UInt32 n)
  14. { return ((n & (n - 1)) == 0); }
  15. SInt32 floorLog2(UInt32 n)
  16. {
  17. SInt32 p = 0;
  18. if (n == 0) return -1;
  19. if (n & 0xffff0000) { p += 16; n >>= 16; }
  20. if (n & 0x0000ff00) { p += 8; n >>= 8; }
  21. if (n & 0x000000f0) { p += 4; n >>= 4; }
  22. if (n & 0x0000000c) { p += 2; n >>= 2; }
  23. if (n & 0x00000002) { p += 1; }
  24. return p;
  25. }
  26. SInt32 ceilLog2(UInt32 n)
  27. { return floorLog2(n - 1) + 1; }
  28. // http://stackoverflow.com/a/6998789/199554
  29. UInt64 countBits(UInt64 n)
  30. {
  31. UInt64 result = 0;
  32. if(n == 0)
  33. return 0;
  34. for(result = 1; n &= n - 1; ++result)
  35. ;
  36. return result;
  37. }