From 271500d4339ce3890c2c3e19ae7da9bc2e2c4049 Mon Sep 17 00:00:00 2001 From: d_m Date: Thu, 9 Nov 2023 12:59:21 -0500 Subject: [PATCH] Implement bc15add with test. --- src/base3.c | 28 ++++++++++++++++++++++++++++ src/bcb.c | 28 ++++++++++++++++++++++++++++ src/bcb.h | 2 ++ 3 files changed, 58 insertions(+) diff --git a/src/base3.c b/src/base3.c index b694a24..eef6b0c 100644 --- a/src/base3.c +++ b/src/base3.c @@ -65,5 +65,33 @@ main(int argc, char **argv) printf("%4d -> %4d ", 1 << i, uc15int(intuc15(1 << i))), phep(intuc15(1 << i), 5); LB } + + printf("\nbc15 addition:\n"); + int total = 0; + int passed = 0; + for(int i = -50; i <= 50; i += 1) { + for(int j = -50; j <= 50; j += 1) { + bc15 a = intbc15(i); + bc15 b = intbc15(j); + bc15 c = bc15add(a, b); + int k = bc15int(c); + int l = i + j; + total += 1; + if (k == l) { + passed += 1; + } else { + printf("FAIL "); + printf(" % 3d + % 3d = % 5d (", i, j, k); + pbal(a, 7); + printf(" (+) "); + pbal(b, 7); + printf(" (=) "); + pbal(c, 7); + printf(")\n"); + } + } + } + printf(" %d of %d test cases passed\n", passed, total); + return 0; } diff --git a/src/bcb.c b/src/bcb.c index a949ffc..6f68433 100644 --- a/src/bcb.c +++ b/src/bcb.c @@ -142,6 +142,34 @@ bc15int(bc15 t) return acc; } +bc15 +bc15add(bc15 a, bc15 b) +{ + bc15 acc = 0; + int i, carry = 0; + for (i = 0; i < 30 && (carry != 0 || (a>>i) != 0 || (b>>i) != 0); i += 2) { + int digit = carry; + carry = 0; + bc15carry((a >> i) & 0x3, &digit, &carry); + bc15carry((b >> i) & 0x3, &digit, &carry); + acc |= (digit << i);; + } + return acc; +} + +void +bc15carry(int next, int *digit, int *carry) +{ + int sum = *digit + next; + int part = sum & 0x3; + if (part == 2) { + *carry = (*carry + (sum >> 1)) & 0x3; + *digit = (sum ^ 4) >> 1; + } else { + *digit = part; + } +} + // Unsigned(TODO: migrate to 11-00-01 encoding) int diff --git a/src/bcb.h b/src/bcb.h index b7bc6d1..0360985 100644 --- a/src/bcb.h +++ b/src/bcb.h @@ -47,6 +47,8 @@ void pbc3(bc3 t); // 15 Trits bc15 intbc15(int n); int bc15int(bc15 t); +bc15 bc15add(bc15 a, bc15 b); +void bc15carry(int sum, int *digit, int *carry); // Unsigned int uc15int(uc15 t); -- 2.45.2