interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / compiler / progs / popcount.osc

31 lines · 728 bytes Raw Blame History
1// entry: pop64 pop8 pop_kernighan
2// expect-run: pop64 255 -> 8
3// expect-run: pop64 18446744073709551615 -> 64
4// expect-run: pop8 255 -> 8
5// expect-run: pop_kernighan 4294967295 -> 32
6// population count three ways.
7fn pop64(x: u64) -> u32 {
8 let mut n: u32 = 0;
9 for i in 0 .. 64 {
10 if (x >> (i as u64)) & 1 == 1 { n = n + 1; }
11 }
12 return n;
13}
14
15fn pop8(x: u8) -> u8 {
16 let mut v: u8 = x;
17 v = (v & 0x55) + ((v >> 1) & 0x55);
18 v = (v & 0x33) + ((v >> 2) & 0x33);
19 v = (v & 0x0f) + ((v >> 4) & 0x0f);
20 return v;
21}
22
23fn pop_kernighan(x: u32) -> u32 {
24 let mut v: u32 = x;
25 let mut n: u32 = 0;
26 while v != 0 bound 32 {
27 v = v & (v - 1);
28 n = n + 1;
29 }
30 return n;
31}