Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/libsnes/bsnes/nall/bit.hpp
2 views
1
#ifndef NALL_BIT_HPP
2
#define NALL_BIT_HPP
3
4
namespace nall {
5
template<unsigned bits>
6
constexpr inline uintmax_t uclamp(const uintmax_t x) {
7
enum : uintmax_t { b = 1ull << (bits - 1), y = b * 2 - 1 };
8
return y + ((x - y) & -(x < y)); //min(x, y);
9
}
10
11
template<unsigned bits>
12
constexpr inline uintmax_t uclip(const uintmax_t x) {
13
//zero 17-jun-2015 - revised to use more standard constexpr behaviour
14
//enum : uintmax_t { b = 1ull << (bits - 1), m = b * 2 - 1 };
15
//return (x & m); //test
16
return (x & ((uintmax_t)(((uintmax_t)(1ull << (bits - 1))) * 2 - 1)));
17
}
18
19
template<unsigned bits>
20
constexpr inline intmax_t sclamp(const intmax_t x) {
21
//zero 17-jun-2015 - revised to use more standard constexpr behaviour
22
//enum : intmax_t { b = 1ull << (bits - 1), m = b - 1 };
23
//(intmax_t)(1ull << (bits - 1)) //b
24
//(((intmax_t)(1ull << (bits - 1))) - 1) //m
25
//return (x > m) ? m : (x < -b) ? -b : x;
26
return (x > (((intmax_t)(1ull << (bits - 1))) - 1)) ? (((intmax_t)(1ull << (bits - 1))) - 1) : (x < -((intmax_t)(1ull << (bits - 1)))) ? -((intmax_t)(1ull << (bits - 1))) : x; //test
27
}
28
29
template<unsigned bits>
30
constexpr inline intmax_t sclip(const intmax_t x) {
31
//zero 17-jun-2015 - revised to use more standard constexpr behaviour
32
//enum : uintmax_t { b = 1ull << (bits - 1), m = b * 2 - 1 }; //test
33
return ((x & ((uintmax_t)(((uintmax_t)(1ull << (bits - 1))) * 2 - 1))) ^ ((uintmax_t)(1ull << (bits - 1)))) - ((uintmax_t)(1ull << (bits - 1)));
34
}
35
36
namespace bit {
37
//lowest(0b1110) == 0b0010
38
constexpr inline uintmax_t lowest(const uintmax_t x) {
39
return x & -x;
40
}
41
42
//clear_lowest(0b1110) == 0b1100
43
constexpr inline uintmax_t clear_lowest(const uintmax_t x) {
44
return x & (x - 1);
45
}
46
47
//set_lowest(0b0101) == 0b0111
48
constexpr inline uintmax_t set_lowest(const uintmax_t x) {
49
return x | (x + 1);
50
}
51
52
//count number of bits set in a byte
53
inline unsigned count(uintmax_t x) {
54
unsigned count = 0;
55
do count += x & 1; while(x >>= 1);
56
return count;
57
}
58
59
//round up to next highest single bit:
60
//round(15) == 16, round(16) == 16, round(17) == 32
61
inline uintmax_t round(uintmax_t x) {
62
if((x & (x - 1)) == 0) return x;
63
while(x & (x - 1)) x &= x - 1;
64
return x << 1;
65
}
66
}
67
}
68
69
#endif
70
71