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 5 // This file defines some bit utilities. 6 7 #ifndef BASE_BITS_H_ 8 #define BASE_BITS_H_ 9 10 #include <stddef.h> 11 #include <stdint.h> 12 13 #include "base/logging.h" 14 15 namespace base { 16 namespace bits { 17 18 // Returns the integer i such as 2^i <= n < 2^(i+1) 19 inline int Log2Floor(uint32_t n) { 20 if (n == 0) 21 return -1; 22 int log = 0; 23 uint32_t value = n; 24 for (int i = 4; i >= 0; --i) { 25 int shift = (1 << i); 26 uint32_t x = value >> shift; 27 if (x != 0) { 28 value = x; 29 log += shift; 30 } 31 } 32 DCHECK_EQ(value, 1u); 33 return log; 34 } 35 36 // Returns the integer i such as 2^(i-1) < n <= 2^i 37 inline int Log2Ceiling(uint32_t n) { 38 if (n == 0) { 39 return -1; 40 } else { 41 // Log2Floor returns -1 for 0, so the following works correctly for n=1. 42 return 1 + Log2Floor(n - 1); 43 } 44 } 45 46 // Round up |size| to a multiple of alignment, which must be a power of two. 47 inline size_t Align(size_t size, size_t alignment) { 48 DCHECK_EQ(alignment & (alignment - 1), 0u); 49 return (size + alignment - 1) & ~(alignment - 1); 50 } 51 52 } // namespace bits 53 } // namespace base 54 55 #endif // BASE_BITS_H_ 56