isa: martins sample
[calu.git] / 2_isa / src / bittwiddling.s
1
2 .data
3 .align 32
4 ;#define B0 (0x55555555)
5 B0:
6 .dw 0x55555555
7 ;#define B1 (0x33333333)
8 B1:
9 .dw 0x33333333
10 ;#define B2 (0x0F0F0F0F)
11 B2:
12 .dw 0x0F0F0F0F
13 ;#define B3 (0x001F001F)
14 B3:
15 .dw 0x001F001F
16 ;#define B4 (0x0000003F)
17 B4:
18 .dw 0x0000003F
19
20 .text
21
22 ;int countbits(int x) {
23 countbits:
24         ;x == r1
25         
26         ;load address of B0 into r3
27         ldil r3,low(B0);
28         ldih r3,high(B0);
29
30         ;x = (x & B0) + ((x >>  1) & B0);
31         ;r0 = (x >> 1)
32         lrs r0,r1,1;
33         
34         ;load B0 into r2
35         ldx r2, r3;
36
37         ;(x >> 1) & B0  
38         and r0, r0, r2;
39
40         ;x & B0
41         and r1, r1, r2;
42         
43         ;x = (x & B0) + ((x >>  1) & B0);
44         add r0, r0, r1;
45
46         ;load B1 into r2, use displacment for address of B1 (or add?)
47         ldx r2, (r3)(B1-B0);
48
49         ;x = (x & B1) + ((x >>  2) & B1);
50         lrs r1, r0, 2;
51         and r1, r1, r2;
52
53         and r0, r0, r2;
54
55         add r0, r0, r1;
56
57         ;x = (x + (x >>  4)) & B2;
58         ldx r2, (r3)(B2-B0);
59
60         lrs r1, r0, 4;
61         and r1, r1, r2;
62         and r0, r0, r2;
63
64         add r0, r0, r1;
65
66         ;x = (x + (x >>  8)) /*& B3 */
67         lrs r1, r0, 8;
68         add r0, r0, r1;
69
70         ldx r2, (r3)(B4-B0);
71         ;x = (x + (x >> 16)) & B4;
72         lrs r1, r0, 16;
73         add r0, r0, r1;
74         and r0, r0, r2;
75
76         ;return x;
77         ret;
78 ;}
79
80 int computeparity(int x) 
81         x ^= x >> 16;
82         x ^= x >> 8;
83         x ^= x >> 4;
84         x &= 0xf;
85         return (0x6996 >> x) & 1;
86 }
87
88 void main(void) {
89         countbits(B0);
90         computeparity(B0);
91         computeparity(B0+1);
92 }