furnace/src/engine/bsr.h

87 lines
1.8 KiB
C
Raw Normal View History

/**
* Furnace Tracker - multi-system chiptune tracker
2024-01-17 02:26:57 +00:00
* Copyright (C) 2021-2024 tildearrow and contributors
*
* This program 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; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#if defined( _MSC_VER )
#include <intrin.h>
static inline int bsr(unsigned short v) {
unsigned long idx;
if (_BitScanReverse(&idx,(unsigned long)v)) {
return idx;
}
else {
return -1;
}
}
2024-01-24 21:21:42 +00:00
static inline int bsr32(unsigned int v) {
unsigned long idx;
if (_BitScanReverse(&idx,(unsigned long)v)) {
return idx;
} else {
return -1;
}
}
#elif defined( __GNUC__ )
2024-01-24 21:21:42 +00:00
static inline int bsr(unsigned short v) {
if (v) {
return 32 - __builtin_clz(v);
2024-01-24 21:21:42 +00:00
} else {
return -1;
}
2024-01-24 21:21:42 +00:00
}
static inline int bsr32(unsigned int v) {
if (v) {
return 32 - __builtin_clz(v);
} else {
return -1;
}
}
#else
2024-01-24 21:21:42 +00:00
static inline int bsr(unsigned short v) {
unsigned short mask = 0x8000;
for (int i = 15; i >= 0; --i) {
if (v&mask)
return (int)i;
mask>>=1;
}
return -1;
}
2024-01-24 21:21:42 +00:00
static inline int bsr32(unsigned int v) {
unsigned int mask = 0x80000000;
for (int i = 31; i >= 0; --i) {
if (v&mask)
return (int)i;
mask>>=1;
}
return -1;
}
#endif