Systemnahe Programmierung in C: Bit-Operationen |
1/* Makros zur Bitmanipulation */
2
3#include <limits.h>
4
5typedef unsigned long int Set;
6
7#define SET_BITS (CHAR_BIT * sizeof (Set))
8
9
10#define check(i) ( (Set)(i) < SET_BITS )
11
12#define emptyset ( (Set)0 )
13
14#define singleset(i) ( ((Set)1) << (i) )
15
16#define intersect(s1,s2) ( (s1) & (s2) )
17
18#define union(s1,s2) ( (s1) | (s2) )
19
20#define add(s,i) union(s, singleset(i))
21
22#define exor(s1,s2) ( (s1) ^ (s2) )
23
24#define complement(s) ( ~(s) )
25
26#define diff(s1,s2) intersect(s1, complement(s2))
27
28#define element(i,s) ( intersect (singleset(i),s) != emptyset )
29
30#define first_n_elems(n) ( singleset(n) - 1 )
31
32#define forallelems(i,s) \
33 for ((i) = 0; (i) < SET_BITS; ++(i)) \
34 if (element((i),(s)))
35
36/*----------------------------------------*/
37
38extern int cardinality (Set x);
39
40extern int cardinality1 (Set x);
41
42extern void printset (Set s);
|
1#include <stdio.h>
2
3#include "set.h"
4
5/*----------------------------------------*/
6
7int
8cardinality (Set x)
9{
10 int count = 0;
11 int j;
12
13 /* wordlength iterations */
14
15 forallelems (j, x)
16 ++ count;
17
18 return count;
19}
20
21/*----------------------------------------*/
22
23int
24cardinality1 (Set x)
25{
26 int count = 0;
27
28 /* card iterations */
29 /* only usable for 2-Complement */
30
31 while (x != emptyset)
32 {
33 /* some comment would be useful */
34
35 x ^= (x & -x);
36 ++count;
37 }
38
39 return count;
40}
41
42/*----------------------------------------*/
43
44void
45printset (Set s)
46{
47 int first = 1;
48 int e;
49
50 forallelems (e, s)
51 {
52 printf ("%s%d", (first) ? "{" : ",", e);
53 first = 0;
54 }
55
56 if (first)
57 printf ("{");
58
59 printf ("}");
60}
|
Sieb des Eratosthenes
|
1typedef ... Element;
2
3void
4swap (Element * x, Element * y)
5{
6 *x ^= *y;
7 *y ^= *x;
8 *x ^= *y;
9}
|
Letzte Änderung: 11.01.2007 | © Prof. Dr. Uwe Schmidt |