-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog2.h
More file actions
41 lines (34 loc) · 705 Bytes
/
log2.h
File metadata and controls
41 lines (34 loc) · 705 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* (c) Copyright 2001 -- Anders Torger
*
* This program is open source. For license terms, see the LICENSE file.
*
*/
#ifndef _LOG2_H_
#define _LOG2_H_
#include <inttypes.h>
/* FIXME: these implementations does not look very elegant */
static inline int
log2_get(uint32_t x)
{
int lg;
for (lg = 0; (x & 1) == 0 && lg < 32; x = x >> 1, lg++);
if (lg == 32 || (x & ~1) != 0) {
return -1;
}
return lg;
}
static inline int
log2_roof(uint32_t x)
{
int lg;
for (lg = 31; (x & (1 << lg)) == 0 && lg > 0; lg--);
if (lg == 0 || (lg == 31 && (x & 0x7FFFFFFF) != 0)) {
return -1;
}
if ((x & ~(1 << lg)) != 0) {
lg++;
}
return lg;
}
#endif