1 // Copyright (c) 2013 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 THIRD_PARTY_BASE_BITS_H_ 8 #define THIRD_PARTY_BASE_BITS_H_ 9 10 #include <type_traits> 11 12 namespace pdfium { 13 namespace base { 14 namespace bits { 15 16 // TODO(thestig): When C++20 is required, replace with std::has_single_bit(). 17 // Returns true iff |value| is a power of 2. 18 template <typename T, typename = std::enable_if<std::is_integral<T>::value>> IsPowerOfTwo(T value)19constexpr inline bool IsPowerOfTwo(T value) { 20 // From "Hacker's Delight": Section 2.1 Manipulating Rightmost Bits. 21 // 22 // Only positive integers with a single bit set are powers of two. If only one 23 // bit is set in x (e.g. 0b00000100000000) then |x-1| will have that bit set 24 // to zero and all bits to its right set to 1 (e.g. 0b00000011111111). Hence 25 // |x & (x-1)| is 0 iff x is a power of two. 26 return value > 0 && (value & (value - 1)) == 0; 27 } 28 29 } // namespace bits 30 } // namespace base 31 } // namespace pdfium 32 33 #endif // THIRD_PARTY_BASE_BITS_H_ 34