| 1 | (* CLZ(x), CTZ(x) and POPCOUNT(x) count the bits of x (report section |
| 2 | 6.1): of each unsigned type, at its own width, with 0 counting the |
| 3 | whole width; of variables, of a value an operator wrapped, beside |
| 4 | other values, and of constants, in a constant too; and POPCOUNT of a |
| 5 | set. Each line is CLZ, CTZ and POPCOUNT of one value. *) |
| 6 | module Count; |
| 7 | import Out; |
| 8 | |
| 9 | type |
| 10 | Day = (mon, tue, wed, thu, fri, sat, sun); |
| 11 | Days = set of Day; |
| 12 | |
| 13 | const |
| 14 | Top = CLZ(U64(1)); (* 63 *) |
| 15 | Low = CTZ(U16(8)); (* 3 *) |
| 16 | Ones = POPCOUNT(U32(0F0F0H)); (* 8 *) |
| 17 | Week = POPCOUNT({mon, wed, sun}); (* 3 *) |
| 18 | None = CLZ(U8(0)) + CTZ(U32(0)); (* 8 + 32 *) |
| 19 | |
| 20 | proc show(a, b, c: INT); |
| 21 | begin |
| 22 | Out.int(a); Out.str(" "); Out.int(b); Out.str(" "); Out.int(c); Out.ln; |
| 23 | end; |
| 24 | |
| 25 | proc u8(x: U8); |
| 26 | begin |
| 27 | show(CLZ(x), CTZ(x), POPCOUNT(x)); |
| 28 | end; |
| 29 | |
| 30 | proc u16(x: U16); |
| 31 | begin |
| 32 | show(CLZ(x), CTZ(x), POPCOUNT(x)); |
| 33 | end; |
| 34 | |
| 35 | proc u32(x: U32); |
| 36 | begin |
| 37 | show(CLZ(x), CTZ(x), POPCOUNT(x)); |
| 38 | end; |
| 39 | |
| 40 | proc u64(x: U64); |
| 41 | begin |
| 42 | show(CLZ(x), CTZ(x), POPCOUNT(x)); |
| 43 | end; |
| 44 | |
| 45 | proc uint(x: UINT); |
| 46 | begin |
| 47 | show(CLZ(x), CTZ(x), POPCOUNT(x)); |
| 48 | end; |
| 49 | |
| 50 | proc main*; |
| 51 | var c: U32; d: U64; n: INT; s, none: Days; |
| 52 | begin |
| 53 | u8(0); u8(1); u8(80H); u8(0FFH); u8(28H); |
| 54 | u16(0); u16(1); u16(8000H); u16(0FFFFH); u16(0F00H); |
| 55 | u32(0); u32(1); u32(80000000H); u32(0FFFFFFFFH); u32(10100H); |
| 56 | u64(0); u64(1); u64(8000000000000000H); u64(0FFFFFFFFFFFFFFFFH); u64(0F0000000000000F0H); |
| 57 | uint(0); uint(1); uint(UINT(1) shl 63); uint(UINT(0FFFFFFFFFFFFFFFFH)); uint(UINT(6) shl 40); |
| 58 | (* constants *) |
| 59 | show(Top, Low, Ones); |
| 60 | show(Week, None, POPCOUNT(U64(0FFFFFFFFFFFFFFFFH))); |
| 61 | show(CLZ(U16(1)), CTZ(U8(0)), POPCOUNT(U8(0))); |
| 62 | (* a U32 that wrapped to 0 is 0, whatever the machine held above it *) |
| 63 | c := 80000000H; |
| 64 | show(CLZ(c + c), CTZ(c + c), POPCOUNT(c + c)); |
| 65 | (* beside other values on the stack *) |
| 66 | d := 0F0H; |
| 67 | n := 1000 + CLZ(d) * 10 + CTZ(d) * 100 + POPCOUNT(d) * (POPCOUNT(d) + 1); |
| 68 | Out.int(n); Out.ln; |
| 69 | s := {tue, thu, sat, sun}; |
| 70 | show(POPCOUNT(s), POPCOUNT(s - {sun}), POPCOUNT(none)); |
| 71 | end; |
| 72 | |
| 73 | end Count. |