| 1 | (* ROL(x, n) and ROR(x, n) rotate x by n bits modulo its width (report |
| 2 | section 6.1): of each unsigned type, by 0, by the width and past it, |
| 3 | by a negative or signed count, with x and n variables or constants; |
| 4 | and a constant made by ROL. Each line is the left rotation, then the |
| 5 | right one. *) |
| 6 | module Rotate; |
| 7 | import Out; |
| 8 | |
| 9 | const |
| 10 | Eight = ROL(U32(1), 3); |
| 11 | Top = ROR(U64(1), 1) | ROL(U64(1), 64); |
| 12 | |
| 13 | (* the two rotations of x by n, a variable count *) |
| 14 | proc u8(x: U8; n: INT); |
| 15 | begin |
| 16 | Out.hex(U64(ROL(x, n)), 2); Out.str(" "); Out.hex(U64(ROR(x, n)), 2); Out.ln; |
| 17 | end; |
| 18 | |
| 19 | proc u16(x: U16; n: I8); |
| 20 | begin |
| 21 | Out.hex(U64(ROL(x, n)), 4); Out.str(" "); Out.hex(U64(ROR(x, n)), 4); Out.ln; |
| 22 | end; |
| 23 | |
| 24 | proc u32(x: U32; n: U64); |
| 25 | begin |
| 26 | Out.hex(U64(ROL(x, n)), 8); Out.str(" "); Out.hex(U64(ROR(x, n)), 8); Out.ln; |
| 27 | end; |
| 28 | |
| 29 | proc u64(x: U64; n: I64); |
| 30 | begin |
| 31 | Out.hex(ROL(x, n), 16); Out.str(" "); Out.hex(ROR(x, n), 16); Out.ln; |
| 32 | end; |
| 33 | |
| 34 | proc uint(x: UINT; n: U8); |
| 35 | begin |
| 36 | Out.hex(U64(ROL(x, n)), 16); Out.str(" "); Out.hex(U64(ROR(x, n)), 16); Out.ln; |
| 37 | end; |
| 38 | |
| 39 | proc main*; |
| 40 | var a: U8; b: U16; c: U32; d: U64; n: INT; |
| 41 | begin |
| 42 | u8(81H, 1); u8(81H, 0); u8(81H, 8); u8(81H, 9); u8(81H, 33); u8(81H, -1); u8(0B4H, 4); |
| 43 | u16(8001H, 1); u16(8001H, 16); u16(8001H, 33); u16(1234H, -4); |
| 44 | u32(80000001H, 1); u32(80000001H, 32); u32(80000001H, 33); u32(12345678H, 7); |
| 45 | u64(8000000000000001H, 1); u64(8000000000000001H, 64); u64(8000000000000001H, -63); |
| 46 | u64(0123456789ABCDEFH, 12); |
| 47 | uint(1, 63); uint(1, 200); |
| 48 | |
| 49 | (* a constant count, an immediate *) |
| 50 | a := 81H; b := 8001H; c := 12345678H; d := 0123456789ABCDEFH; |
| 51 | Out.hex(U64(ROL(a, 1)), 2); Out.str(" "); Out.hex(U64(ROR(a, 9)), 2); Out.str(" "); Out.hex(U64(ROL(a, -1)), 2); Out.ln; |
| 52 | Out.hex(U64(ROL(b, 17)), 4); Out.str(" "); Out.hex(U64(ROR(b, 0)), 4); Out.ln; |
| 53 | Out.hex(U64(ROR(c, 7)), 8); Out.str(" "); Out.hex(U64(ROL(c, 32)), 8); Out.ln; |
| 54 | Out.hex(ROL(d, 12), 16); Out.str(" "); Out.hex(ROR(d, 68), 16); Out.ln; |
| 55 | |
| 56 | (* a constant x, a variable count *) |
| 57 | n := 3; |
| 58 | Out.hex(U64(ROL(U8(81H), n)), 2); Out.str(" "); Out.hex(U64(ROR(U32(1), n)), 8); Out.ln; |
| 59 | |
| 60 | (* both constants, folded *) |
| 61 | Out.hex(U64(ROL(U8(81H), 1)), 2); Out.str(" "); Out.hex(U64(ROR(U8(81H), 1)), 2); Out.str(" "); |
| 62 | Out.hex(U64(ROR(U16(8001H), 17)), 4); Out.str(" "); Out.hex(U64(ROR(U32(12345678H), -25)), 8); Out.ln; |
| 63 | Out.int(I64(Eight)); Out.str(" "); Out.hex(Top, 16); Out.ln; |
| 64 | end; |
| 65 | |
| 66 | end Rotate. |