summaryrefslogtreecommitdiffstats
path: root/src/lib/clog2.c
blob: 5e0d591de4ff3a2267cfd80d1760639fb9e0ae58 (plain)
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
#include <console/console.h>
#include <lib.h>

/* Assume 8 bits per byte */
#define CHAR_BIT 8

unsigned long log2(unsigned long x)
{
	/* assume 8 bits per byte. */
	unsigned long pow = sizeof(x) * CHAR_BIT - 1ULL;
	unsigned long i = 1ULL << pow;

	if (!x) {
		printk(BIOS_WARNING, "%s called with invalid parameter of 0\n",
			__func__);
		return -1;
	}

	for (; i > x; i >>= 1, pow--);

	return pow;
}

unsigned long log2_ceil(unsigned long x)
{
	unsigned long pow;

	if (!x)
		return -1;

	pow = log2(x);

	if (x > (1ULL << pow))
		pow++;

	return pow;
}