bits.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file bits.c
  7. *
  8. * \brief Count the bits in an integer, manipulate powers of 2, etc.
  9. **/
  10. #include "lib/intmath/bits.h"
  11. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  12. int
  13. tor_log2(uint64_t u64)
  14. {
  15. int r = 0;
  16. if (u64 >= (UINT64_C(1)<<32)) {
  17. u64 >>= 32;
  18. r = 32;
  19. }
  20. if (u64 >= (UINT64_C(1)<<16)) {
  21. u64 >>= 16;
  22. r += 16;
  23. }
  24. if (u64 >= (UINT64_C(1)<<8)) {
  25. u64 >>= 8;
  26. r += 8;
  27. }
  28. if (u64 >= (UINT64_C(1)<<4)) {
  29. u64 >>= 4;
  30. r += 4;
  31. }
  32. if (u64 >= (UINT64_C(1)<<2)) {
  33. u64 >>= 2;
  34. r += 2;
  35. }
  36. if (u64 >= (UINT64_C(1)<<1)) {
  37. // u64 >>= 1; // not using this any more.
  38. r += 1;
  39. }
  40. return r;
  41. }
  42. /** Return the power of 2 in range [1,UINT64_MAX] closest to <b>u64</b>. If
  43. * there are two powers of 2 equally close, round down. */
  44. uint64_t
  45. round_to_power_of_2(uint64_t u64)
  46. {
  47. int lg2;
  48. uint64_t low;
  49. uint64_t high;
  50. if (u64 == 0)
  51. return 1;
  52. lg2 = tor_log2(u64);
  53. low = UINT64_C(1) << lg2;
  54. if (lg2 == 63)
  55. return low;
  56. high = UINT64_C(1) << (lg2+1);
  57. if (high - u64 < u64 - low)
  58. return high;
  59. else
  60. return low;
  61. }
  62. /** Return the number of bits set in <b>v</b>. */
  63. int
  64. n_bits_set_u8(uint8_t v)
  65. {
  66. static const int nybble_table[] = {
  67. 0, /* 0000 */
  68. 1, /* 0001 */
  69. 1, /* 0010 */
  70. 2, /* 0011 */
  71. 1, /* 0100 */
  72. 2, /* 0101 */
  73. 2, /* 0110 */
  74. 3, /* 0111 */
  75. 1, /* 1000 */
  76. 2, /* 1001 */
  77. 2, /* 1010 */
  78. 3, /* 1011 */
  79. 2, /* 1100 */
  80. 3, /* 1101 */
  81. 3, /* 1110 */
  82. 4, /* 1111 */
  83. };
  84. return nybble_table[v & 15] + nybble_table[v>>4];
  85. }