1 |
|
/* |
2 |
|
** Copyright (C) 2018 Martin Brain |
3 |
|
** |
4 |
|
** See the file LICENSE for licensing information. |
5 |
|
*/ |
6 |
|
|
7 |
|
/* |
8 |
|
** common.h |
9 |
|
** |
10 |
|
** Martin Brain |
11 |
|
** martin.brain@cs.ox.ac.uk |
12 |
|
** 05/08/14 |
13 |
|
** |
14 |
|
** Commonly used utility functions. |
15 |
|
** |
16 |
|
*/ |
17 |
|
|
18 |
|
#include <assert.h> |
19 |
|
#include <stdint.h> |
20 |
|
|
21 |
|
#include "symfpu/utils/properties.h" |
22 |
|
|
23 |
|
#ifndef SYMFPU_COMMON |
24 |
|
#define SYMFPU_COMMON |
25 |
|
|
26 |
|
namespace symfpu { |
27 |
|
template <class T> |
28 |
1166 |
T previousPowerOfTwo (T x) { |
29 |
1166 |
assert(x > 1); |
30 |
|
//PRECONDITION(x > 1); |
31 |
|
|
32 |
1166 |
T current = 1; |
33 |
1166 |
T next = current << 1; |
34 |
|
|
35 |
7682 |
while (next < x) { |
36 |
3258 |
current = next; |
37 |
3258 |
next <<= 1; |
38 |
|
} |
39 |
|
|
40 |
1166 |
return current; |
41 |
|
} |
42 |
|
|
43 |
|
template <class T> |
44 |
|
T leftmostBit (T x) { |
45 |
|
assert(x > 1); |
46 |
|
//PRECONDITION(x > 1); |
47 |
|
|
48 |
|
T current = 1; |
49 |
|
T next = current << 1; |
50 |
|
|
51 |
|
while (next <= x) { |
52 |
|
current = next; |
53 |
|
next <<= 1; |
54 |
|
} |
55 |
|
|
56 |
|
return current; |
57 |
|
} |
58 |
|
|
59 |
|
|
60 |
|
// The number of bits required to represent a number |
61 |
|
// == the position of the leading 0 + 1 |
62 |
|
// == ceil(log_2(value + 1)) |
63 |
|
template <class T> |
64 |
734065 |
T bitsToRepresent (const T value) { |
65 |
734065 |
T i = 0; |
66 |
|
//unsigned T working = *((unsigned T)&value); // Implementation defined for signed types |
67 |
734065 |
T working = value; |
68 |
|
|
69 |
6005167 |
while (working != 0) { |
70 |
2635551 |
++i; |
71 |
2635551 |
working >>= 1; |
72 |
|
} |
73 |
|
|
74 |
734065 |
return i; |
75 |
|
} |
76 |
|
|
77 |
|
template <class T> |
78 |
35 |
T positionOfLeadingOne (const T value) { |
79 |
|
//PRECONDITION(value != 0); |
80 |
35 |
assert(value != 0); |
81 |
|
|
82 |
35 |
T i = 0; |
83 |
|
//unsigned T working = *((unsigned T)&value); // Implementation defined for signed types |
84 |
35 |
T working = value; |
85 |
|
|
86 |
381 |
while (working != 0) { |
87 |
173 |
++i; |
88 |
173 |
working >>= 1; |
89 |
|
} |
90 |
|
|
91 |
35 |
return i - 1; |
92 |
|
} |
93 |
|
} |
94 |
|
|
95 |
|
#endif |