OpenTTD Source  1.11.0-beta2
bitmath_func.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "bitmath_func.hpp"
12 
13 #include "../safeguards.h"
14 
15 const uint8 _ffb_64[64] = {
16  0, 0, 1, 0, 2, 0, 1, 0,
17  3, 0, 1, 0, 2, 0, 1, 0,
18  4, 0, 1, 0, 2, 0, 1, 0,
19  3, 0, 1, 0, 2, 0, 1, 0,
20  5, 0, 1, 0, 2, 0, 1, 0,
21  3, 0, 1, 0, 2, 0, 1, 0,
22  4, 0, 1, 0, 2, 0, 1, 0,
23  3, 0, 1, 0, 2, 0, 1, 0,
24 };
25 
37 uint8 FindFirstBit(uint32 x)
38 {
39  if (x == 0) return 0;
40  /* The macro FIND_FIRST_BIT is better to use when your x is
41  not more than 128. */
42 
43  uint8 pos = 0;
44 
45  if ((x & 0x0000ffff) == 0) { x >>= 16; pos += 16; }
46  if ((x & 0x000000ff) == 0) { x >>= 8; pos += 8; }
47  if ((x & 0x0000000f) == 0) { x >>= 4; pos += 4; }
48  if ((x & 0x00000003) == 0) { x >>= 2; pos += 2; }
49  if ((x & 0x00000001) == 0) { pos += 1; }
50 
51  return pos;
52 }
53 
65 uint8 FindLastBit(uint64 x)
66 {
67  if (x == 0) return 0;
68 
69  uint8 pos = 0;
70 
71  if ((x & 0xffffffff00000000ULL) != 0) { x >>= 32; pos += 32; }
72  if ((x & 0x00000000ffff0000ULL) != 0) { x >>= 16; pos += 16; }
73  if ((x & 0x000000000000ff00ULL) != 0) { x >>= 8; pos += 8; }
74  if ((x & 0x00000000000000f0ULL) != 0) { x >>= 4; pos += 4; }
75  if ((x & 0x000000000000000cULL) != 0) { x >>= 2; pos += 2; }
76  if ((x & 0x0000000000000002ULL) != 0) { pos += 1; }
77 
78  return pos;
79 }
FindLastBit
uint8 FindLastBit(uint64 x)
Search the last set bit in a 64 bit variable.
Definition: bitmath_func.cpp:65
bitmath_func.hpp
_ffb_64
const uint8 _ffb_64[64]
Lookup table to check which bit is set in a 6 bit variable.
Definition: bitmath_func.cpp:15
FindFirstBit
uint8 FindFirstBit(uint32 x)
Search the first set bit in a 32 bit variable.
Definition: bitmath_func.cpp:37