OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

bitmath_func.cpp
Go to the documentation of this file.
1 /* $Id: bitmath_func.cpp 26482 2014-04-23 20:13:33Z rubidium $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "../stdafx.h"
13 #include "bitmath_func.hpp"
14
15 #include "../safeguards.h"
16
17 const uint8 _ffb_64[64] = {
18 0, 0, 1, 0, 2, 0, 1, 0,
19 3, 0, 1, 0, 2, 0, 1, 0,
20 4, 0, 1, 0, 2, 0, 1, 0,
21 3, 0, 1, 0, 2, 0, 1, 0,
22 5, 0, 1, 0, 2, 0, 1, 0,
23 3, 0, 1, 0, 2, 0, 1, 0,
24 4, 0, 1, 0, 2, 0, 1, 0,
25 3, 0, 1, 0, 2, 0, 1, 0,
26 };
27
39 uint8 FindFirstBit(uint32 x)
40 {
41 if (x == 0) return 0;
42 /* The macro FIND_FIRST_BIT is better to use when your x is
43 not more than 128. */
44
45 uint8 pos = 0;
46
47 if ((x & 0x0000ffff) == 0) { x >>= 16; pos += 16; }
48 if ((x & 0x000000ff) == 0) { x >>= 8; pos += 8; }
49 if ((x & 0x0000000f) == 0) { x >>= 4; pos += 4; }
50 if ((x & 0x00000003) == 0) { x >>= 2; pos += 2; }
51 if ((x & 0x00000001) == 0) { pos += 1; }
52
53 return pos;
54 }
55
67 uint8 FindLastBit(uint64 x)
68 {
69 if (x == 0) return 0;
70
71 uint8 pos = 0;
72
73 if ((x & 0xffffffff00000000ULL) != 0) { x >>= 32; pos += 32; }
74 if ((x & 0x00000000ffff0000ULL) != 0) { x >>= 16; pos += 16; }
75 if ((x & 0x000000000000ff00ULL) != 0) { x >>= 8; pos += 8; }
76 if ((x & 0x00000000000000f0ULL) != 0) { x >>= 4; pos += 4; }
77 if ((x & 0x000000000000000cULL) != 0) { x >>= 2; pos += 2; }
78 if ((x & 0x0000000000000002ULL) != 0) { pos += 1; }
79
80 return pos;
81 }