Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Created Sep 2, 2021
Embed
What would you like to do?
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