bits.h 1012 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (c) 2009 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // This file defines some bit utilities.
  5. #ifndef BASE_BITS_H_
  6. #define BASE_BITS_H_
  7. #include "base/basictypes.h"
  8. #include "base/logging.h"
  9. namespace base {
  10. namespace bits {
  11. // Returns the integer i such as 2^i <= n < 2^(i+1)
  12. inline int Log2Floor(uint32_t n) {
  13. if (n == 0)
  14. return -1;
  15. int log = 0;
  16. uint32_t value = n;
  17. for (int i = 4; i >= 0; --i) {
  18. int shift = (1 << i);
  19. uint32_t x = value >> shift;
  20. if (x != 0) {
  21. value = x;
  22. log += shift;
  23. }
  24. }
  25. DCHECK_EQ(value, 1u);
  26. return log;
  27. }
  28. // Returns the integer i such as 2^(i-1) < n <= 2^i
  29. inline int Log2Ceiling(uint32_t n) {
  30. if (n == 0) {
  31. return -1;
  32. } else {
  33. // Log2Floor returns -1 for 0, so the following works correctly for n=1.
  34. return 1 + Log2Floor(n - 1);
  35. }
  36. }
  37. } // namespace bits
  38. } // namespace base
  39. #endif // BASE_BITS_H_