ternary

playing with ternary in C
git clone git://git.rr3.xyz/ternary
Log | Files | Refs

commit f2e4b139be9569a14a1262d161062b1984f691e4
Author: Robert Russell <robert@rr3.xyz>
Date:   Wed,  1 Oct 2025 22:09:19 -0700

Initial commit

Diffstat:
A.gitignore | 1+
AMakefile | 2++
Amain.c | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 61 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +main diff --git a/Makefile b/Makefile @@ -0,0 +1,2 @@ +main: main.c + gcc -Wall -o $@ main.c diff --git a/main.c b/main.c @@ -0,0 +1,58 @@ +#include <rcx/all.h> +#include <stdio.h> +#include <string.h> + +#define LOWER 0x5555555555555555ul +#define UPPER 0xaaaaaaaaaaaaaaaaul + +typedef u64 ut32; + +inline u64 +carry_out(u64 x, u64 y, u64 s) { + return (x & y) | ((x ^ y) & ~s); +} + +ut32 +ut32_add_tritwise(ut32 x, ut32 y) { + u64 sl = (x & LOWER) + (y & LOWER) + LOWER; + u64 sh = (x ^ y) & UPPER; + u64 s = sh ^ sl; + u64 d = (~carry_out(x, y, s) & UPPER) >> 1; + return s - d; +} + +ut32 +ut32_add(ut32 x, ut32 y) { + u64 s = x + y + LOWER; + u64 d = (~carry_out(x, y, s) & UPPER) >> 1; + return s - d; +} + +void +ut32_sprint(char *dst, ut32 x) { + static char trit[4] = "012?"; + + char buf[33]; + buf[32] = '\0'; + + usize i = 32; + while (i > 0) { + buf[--i] = trit[x & 3]; + x >>= 2; + if (x == 0) break; + } + strcpy(dst, buf + i); +} + +int +main(void) { + char buf[33]; + + ut32 x = 0b00011010; + ut32 y = 0b01100001; + ut32 s = ut32_add(x, y); + + ut32_sprint(buf, x); printf("x: %9s\n", buf); + ut32_sprint(buf, y); printf("y: %9s\n", buf); + ut32_sprint(buf, s); printf("s: %9s\n", buf); +}