From fffc370380b9ca8a5fb4f2b1e3cd9ad6709adb6e Mon Sep 17 00:00:00 2001 From: John Date: Thu, 11 Jul 2024 04:02:44 -0500 Subject: [PATCH] sample-code: Expand the capabilities of the sample code --- sample-code/hex.cl | 39 +++++++++++++++++++++++++++++---------- sample-code/math.cl | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 sample-code/math.cl diff --git a/sample-code/hex.cl b/sample-code/hex.cl index 3e00d2e..0c58930 100644 --- a/sample-code/hex.cl +++ b/sample-code/hex.cl @@ -1,12 +1,31 @@ -pub fn hex(mut n: u64) { - let hex_lut = [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', - ]; - for xd in 0..16 { - let n = n >> (15 - xd) * 4; - if n != 0 { - print(hex_lut[n & 0xf]) - } +//! Formats numbers in hexadecimal, octal, or binary +mod math; + +// TODO: casting and/or conversion +const HEX_LUT: Array = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', +]; + +pub fn hex(n: u64) { + let out = "0x"; + for xd in min(count_leading_zeroes(n) / 4, 15)..16 { + out += HEX_LUT[(n >> (15 - xd) * 4) & 0xf] } - println() + out +} + +pub fn oct(n: u64) { + let out = "0o"; + for xd in min((count_leading_zeroes(n) + 2) / 3, 21)..22 { + out += HEX_LUT[(n >> max(63 - (3 * xd), 0)) & 7] + } + out +} + +pub fn bin(n: u64) { + let out = "0b"; + for xd in min(count_leading_zeroes(n), 63)..64 { + out += HEX_LUT[(n >> 63 - xd) & 1] + } + out } diff --git a/sample-code/math.cl b/sample-code/math.cl new file mode 100644 index 0000000..7ba02d2 --- /dev/null +++ b/sample-code/math.cl @@ -0,0 +1,36 @@ +//! Useful math functions + +pub fn max(a: T, b: T) -> T { + (if a < b { b } else { a }) +} + +pub fn min(a: T, b: T) -> T { + (if a > b { b } else { a }) +} + +pub fn count_leading_zeroes(n: u64) -> u64 { + let mut xd = 64; + if n < 0 { + return 0; + } + while n != 0 { + xd -= 1; + n >>= 1; + } + xd +} + +pub fn count_trailing_zeroes(n: u64) -> u64 { + let mut xd = 0; + if n == 0 { + 64 + } else if n < 0 { + 0 + } else { + while n & 1 == 0 { + xd += 1; + n >>= 1; + } + xd + } +}