main.c (1014B)
1 #include <rcx/all.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 #define LOWER 0x5555555555555555ul 6 #define UPPER 0xaaaaaaaaaaaaaaaaul 7 8 typedef u64 ut32; 9 10 inline u64 11 carry_out(u64 x, u64 y, u64 s) { 12 return (x & y) | ((x ^ y) & ~s); 13 } 14 15 ut32 16 ut32_add_tritwise(ut32 x, ut32 y) { 17 u64 sl = (x & LOWER) + (y & LOWER) + LOWER; 18 u64 sh = (x ^ y) & UPPER; 19 u64 s = sh ^ sl; 20 u64 d = (~carry_out(x, y, s) & UPPER) >> 1; 21 return s - d; 22 } 23 24 ut32 25 ut32_add(ut32 x, ut32 y) { 26 u64 s = x + y + LOWER; 27 u64 d = (~carry_out(x, y, s) & UPPER) >> 1; 28 return s - d; 29 } 30 31 void 32 ut32_sprint(char *dst, ut32 x) { 33 static char trit[4] = "012?"; 34 35 char buf[33]; 36 buf[32] = '\0'; 37 38 usize i = 32; 39 while (i > 0) { 40 buf[--i] = trit[x & 3]; 41 x >>= 2; 42 if (x == 0) break; 43 } 44 strcpy(dst, buf + i); 45 } 46 47 int 48 main(void) { 49 char buf[33]; 50 51 ut32 x = 0b00011010; 52 ut32 y = 0b01100001; 53 ut32 s = ut32_add(x, y); 54 55 ut32_sprint(buf, x); printf("x: %9s\n", buf); 56 ut32_sprint(buf, y); printf("y: %9s\n", buf); 57 ut32_sprint(buf, s); printf("s: %9s\n", buf); 58 }