1 //------------------------------------------------------------------------------
2 // GB_log2.h: integer log2 and check if power of 2
3 //------------------------------------------------------------------------------
4 
5 // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
6 // SPDX-License-Identifier: Apache-2.0
7 
8 //------------------------------------------------------------------------------
9 
10 #ifndef GB_LOG2_H
11 #define GB_LOG2_H
12 
13 // # of bits in an unsigned long long, normally 64
14 #define GB_64 (8 * sizeof (unsigned long long))
15 
16 // floor and ceiling of the log2 of an integer.
17 #ifdef __GNUC__
18 // see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
19 #define GB_CLZLL(k)   __builtin_clzll ((unsigned long long) (k))
20 #define GB_CEIL_LOG2(k)  ((uint64_t) ((k) < 2) ? 0 : (GB_64 - GB_CLZLL ((k)-1)))
21 #define GB_FLOOR_LOG2(k) ((uint64_t) ((k) < 2) ? 0 : (GB_64 - GB_CLZLL (k) - 1))
22 #else
23 #define GB_CLZLL(k)   not defined, using log2 instead
24 #define GB_CEIL_LOG2(k)  ((uint64_t) (ceil  (log2 ((double) k))))
25 #define GB_FLOOR_LOG2(k) ((uint64_t) (floor (log2 ((double) k))))
26 #endif
27 
28 // GB_IS_POWER_OF_TWO(k) is true if the unsigned integer k is an exact power of
29 // two, or if k is zero.  This expression should not be used if k is negative.
30 #define GB_IS_POWER_OF_TWO(k) (((k) & ((k) - 1)) == 0)
31 
32 #endif
33 
34