Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Created September 2, 2021 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matu3ba/a6c0a4fab5d9a8a45db3fc8a7ede2c5c to your computer and use it in GitHub Desktop.
Save matu3ba/a6c0a4fab5d9a8a45db3fc8a7ede2c5c to your computer and use it in GitHub Desktop.
helper program to cross check correctness of ctz with simpler algorithm
const std = @import("std");
const maxInt = std.math.maxInt;
const print = std.debug.print;
test "custom number system print ctz" {
//var in: u64 = 0;
var in: u32 = 256;
//var in: u64 = 256;
//var in: u128 = 256;
var x: @TypeOf(in) = 0;
var out: @TypeOf(in) = undefined;
print("\n", .{});
//while (in <= 0xff) : (in += 1) {
while (in < maxInt(@TypeOf(in))) : (in = @mulWithSaturation(in, 2)) {
x = in; // must use temporary for correct iteration
// trailing zeroes simplest computation
if (x == 0) {
out = @bitSizeOf(@TypeOf(x));
} else {
x = (x ^ (x - 1)) >> 1; // Set v's trailing 0s to 1s and zero rest
out = 0;
while (x > 0) : (out += 1) {
x = x >> 1;
}
}
print("{d:>13}", .{in});
print(" {x:>14}", .{in});
print(" {b:>32}", .{in});
print(" {d:>8}\n", .{out}); //result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment