xref: /potrace-1.14/src/bitops.h (revision b3fce824)
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 
6 /* bits.h: this file defines some macros for bit manipulations. We
7    provide a generic implementation, as well as machine- and
8    compiler-specific fast implementations */
9 
10 /* lobit: return the position of the rightmost "1" bit of an int, or
11    32 if none. hibit: return 1 + the position of the leftmost "1" bit
12    of an int, or 0 if none. Note: these functions work on 32-bit
13    integers. */
14 
15 #ifndef BITOPS_H
16 #define BITOPS_H
17 
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
21 
22 /* ---------------------------------------------------------------------- */
23 /* machine specific macros */
24 
25 #if defined(HAVE_I386)
26 
lobit(unsigned int x)27 static inline unsigned int lobit(unsigned int x) {
28   unsigned int res;
29   asm ("bsf	%1,%0\n\t"
30        "jnz	0f\n\t"
31        "movl	$32,%0\n"
32        "0:"
33        : "=r" (res)
34        : "r" (x)
35        : "cc");
36   return res;
37 }
38 
hibit(unsigned int x)39 static inline unsigned int hibit(unsigned int x) {
40   unsigned int res;
41 
42   asm ("bsr	%1,%0\n\t"
43        "jnz	0f\n\t"
44        "movl	$-1,%0\n"
45        "0:"
46        : "=r" (res)
47        : "r" (x)
48        : "cc");
49   return res+1;
50 }
51 
52 /* ---------------------------------------------------------------------- */
53 #else /* generic macros */
54 
lobit(unsigned int x)55 static inline unsigned int lobit(unsigned int x) {
56   unsigned int res = 32;
57   while (x & 0xffffff) {
58     x <<= 8;
59     res -= 8;
60   }
61   while (x) {
62     x <<= 1;
63     res -= 1;
64   }
65   return res;
66 }
67 
hibit(unsigned int x)68 static inline unsigned int hibit(unsigned int x) {
69   unsigned int res = 0;
70   while (x > 0xff) {
71     x >>= 8;
72     res += 8;
73   }
74   while (x) {
75     x >>= 1;
76     res += 1;
77   }
78   return res;
79 }
80 
81 #endif
82 
83 #endif /* BITOPS_H */
84