source: git/factory/si_log2.h @ 96ce32

fieker-DuValspielwiese
Last change on this file since 96ce32 was 8f6246, checked in by Hans Schoenemann <hannes@…>, 4 years ago
fix: typo fo 32bit
  • Property mode set to 100644
File size: 1.1 KB
Line 
1#ifndef SI_LOG2_H
2#define SI_LOG2_H
3#include "factory/factoryconf.h"
4// stolen from:
5// https://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
6static inline int SI_LOG2(int v)
7{
8  const unsigned int b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
9  const unsigned int S[] = {1, 2, 4, 8, 16};
10
11  unsigned int r = 0; // result of log2(v) will go here
12  if (v & b[4]) { v >>= S[4]; r |= S[4]; }
13  if (v & b[3]) { v >>= S[3]; r |= S[3]; }
14  if (v & b[2]) { v >>= S[2]; r |= S[2]; }
15  if (v & b[1]) { v >>= S[1]; r |= S[1]; }
16  if (v & b[0]) { v >>= S[0]; r |= S[0]; }
17  return (int)r;
18}
19#if SIZEOF_LONG==4
20#define SI_LOG2_LONG(A) SI_LOG2(A)
21#else
22static inline int SI_LOG2_LONG(long v)
23{
24  const unsigned long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000UL};
25  const unsigned int S[] = {1, 2, 4, 8, 16, 32};
26
27  unsigned int r = 0; // result of log2(v) will go here
28  if (v & b[5]) { v >>= S[5]; r |= S[5]; }
29  if (v & b[4]) { v >>= S[4]; r |= S[4]; }
30  if (v & b[3]) { v >>= S[3]; r |= S[3]; }
31  if (v & b[2]) { v >>= S[2]; r |= S[2]; }
32  if (v & b[1]) { v >>= S[1]; r |= S[1]; }
33  if (v & b[0]) { v >>= S[0]; r |= S[0]; }
34  return (int)r;
35}
36#endif
37#endif
Note: See TracBrowser for help on using the repository browser.