1 /* Copyright (C) 2001-2017 Peter Selinger.
2 * This file is part of Potrace. It is free software and it is covered
3 * by the GNU General Public License. See the file COPYING for details. */
4
5 /* bits.h: this file defines some macros for bit manipulations. We
6 * provide a generic implementation, as well as machine- and
7 * compiler-specific fast implementations */
8
9 /* lobit: return the position of the rightmost "1" bit of an int, or
10 * 32 if none. hibit: return 1 + the position of the leftmost "1" bit
11 * of an int, or 0 if none. Note: these functions work on 32-bit
12 * integers. */
13
14 #ifndef BITOPS_H
15 #define BITOPS_H
16
17 #ifdef HAVE_CONFIG_H
18 #include <config.h>
19 #endif
20
21 /* ---------------------------------------------------------------------- */
22 /* machine specific macros */
23
24 #if defined( HAVE_I386 )
25
lobit(unsigned int x)26 static inline unsigned int lobit( unsigned int x )
27 {
28 unsigned int res;
29
30 asm ( "bsf %1,%0\n\t"
31 "jnz 0f\n\t"
32 "movl $32,%0\n"
33 "0:"
34 : "=r" ( res )
35 : "r" ( x )
36 : "cc" );
37 return res;
38 }
39
40
hibit(unsigned int x)41 static inline unsigned int hibit( unsigned int x )
42 {
43 unsigned int res;
44
45 asm ( "bsr %1,%0\n\t"
46 "jnz 0f\n\t"
47 "movl $-1,%0\n"
48 "0:"
49 : "=r" ( res )
50 : "r" ( x )
51 : "cc" );
52 return res + 1;
53 }
54
55
56 /* ---------------------------------------------------------------------- */
57 #else /* generic macros */
58
lobit(unsigned int x)59 static inline unsigned int lobit( unsigned int x )
60 {
61 unsigned int res = 32;
62
63 while( x & 0xffffff )
64 {
65 x <<= 8;
66 res -= 8;
67 }
68
69 while( x )
70 {
71 x <<= 1;
72 res -= 1;
73 }
74
75 return res;
76 }
77
78
hibit(unsigned int x)79 static inline unsigned int hibit( unsigned int x )
80 {
81 unsigned int res = 0;
82
83 while( x > 0xff )
84 {
85 x >>= 8;
86 res += 8;
87 }
88
89 while( x )
90 {
91 x >>= 1;
92 res += 1;
93 }
94
95 return res;
96 }
97
98
99 #endif
100
101 #endif /* BITOPS_H */
102