sample-code: Expand the capabilities of the sample code
This commit is contained in:
parent
a646a9e521
commit
fffc370380
@ -1,12 +1,31 @@
|
||||
pub fn hex(mut n: u64) {
|
||||
let hex_lut = [
|
||||
//! 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',
|
||||
];
|
||||
for xd in 0..16 {
|
||||
let n = n >> (15 - xd) * 4;
|
||||
if n != 0 {
|
||||
print(hex_lut[n & 0xf])
|
||||
];
|
||||
|
||||
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
|
||||
}
|
||||
|
36
sample-code/math.cl
Normal file
36
sample-code/math.cl
Normal file
@ -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
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user