all repos — mgba @ 0c5ce511fb7f6c7f8da27638752dd574e413d8ed

mGBA Game Boy Advance Emulator

src/util/math.h (view raw)

 1/* Copyright (c) 2013-2015 Jeffrey Pfau
 2 *
 3 * This Source Code Form is subject to the terms of the Mozilla Public
 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 6#ifndef UTIL_MATH_H
 7#define UTIL_MATH_H
 8
 9#include "util/common.h"
10
11static inline uint32_t popcount32(unsigned bits) {
12	bits = bits - ((bits >> 1) & 0x55555555);
13	bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
14	return (((bits + (bits >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
15}
16
17static inline unsigned clz32(uint32_t bits) {
18#if defined(__GNUC__) || __clang__
19	if (!bits) {
20		return 32;
21	}
22	return __builtin_clz(bits);
23#else
24	static const int table[256] = {
25		8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
26		3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
27		2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
28		2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
29		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
30		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
31		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
32		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
33		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
35		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
36		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
37		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
38		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
39		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
40		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
41	};
42
43	if (bits & 0xFF000000) {
44		return table[bits >> 24];
45	} else if (bits & 0x00FF0000) {
46		return table[bits >> 16] + 8;
47	} else if (bits & 0x0000FF00) {
48		return table[bits >> 8] + 16;
49	}
50	return table[bits] + 24;
51#endif
52}
53
54static inline uint32_t toPow2(uint32_t bits) {
55	if (!bits) {
56		return 0;
57	}
58	unsigned lz = clz32(bits - 1);
59	return 1 << (32 - lz);
60}
61
62#endif