-
Notifications
You must be signed in to change notification settings - Fork 7
/
bitmap.h
76 lines (56 loc) · 1.88 KB
/
bitmap.h
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Copyright (c) 2022 Jiapeng Li <mail@jiapeng.me>
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BITMAP_H
#define __BITMAP_H
//#define BM_1
//#define BM_2
#define BM_1
#define BUILTIN_FUNC
/*
count set bits:
https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
If you want the fastest way, you will need to use non-portable methods.
Windows/MSVC:
_BitScanForward()
_BitScanReverse()
__popcnt()
GCC:
__builtin_ffs()
__builtin_ctz()
__builtin_clz()
__builtin_popcount()
These typically map directly to native hardware instructions. So it doesn't get much faster than these.
But since there's no C/C++ functionality for them, they're only accessible via compiler intrinsics.
*/
#if defined BM_4
typedef uint32_t bm_t;
#define BM_UNIT (sizeof(bm_t) * 8)
#define BM_OFST (5) // 8: 3, 16: 4, 32: 5
#elif defined BM_2
typedef uint16_t bm_t;
#define BM_UNIT (sizeof(bm_t) * 8)
#define BM_OFST (4) // 8: 3, 16: 4, 32: 5
#elif defined BM_1
typedef uint8_t bm_t;
#define BM_UNIT (sizeof(bm_t) * 8)
#define BM_OFST (3) // 8: 3, 16: 4, 32: 5
#endif
bool bit_get(bm_t *bitmap, int index);
void bit_set(bm_t *bitmap, int index);
void bit_clr(bm_t *bitmap, int index);
int bit_count_ones(bm_t *bitmap, int index);
int bit_ffs(bm_t *bitmap, int size);
/* find the nth set */
int bit_fns(bm_t *bitmap, int size, int n);
void bit_xor(bm_t *des, bm_t *src, int size);
bool bit_is_all_clear(bm_t *bitmap, int size);
void bit_clear_all(bm_t *bitmap, int size);
inline int m2t_map(int x, int y, int m);
inline bool m2t_get(bm_t *m2tbm, int x, int y, int m);
inline void m2t_set(bm_t *m2tbm, int x, int y, int m);
inline void m2t_clr(bm_t *m2tbm, int x, int y, int m);
#endif // __BITMAP_H