Skip to content

Instantly share code, notes, and snippets.

@lukewilson2002
Created February 23, 2021 23:50
Show Gist options
  • Save lukewilson2002/83b5cb93849f20c36c43d12e0d77e576 to your computer and use it in GitHub Desktop.
Save lukewilson2002/83b5cb93849f20c36c43d12e0d77e576 to your computer and use it in GitHub Desktop.
Scale integers from of larger size to integers of a smaller size
const std = @import("std");
const maxInt = std.math.maxInt;
fn scaleInt(comptime DestType: type, val: anytype) DestType {
if (@bitSizeOf(@TypeOf(val)) > 16) {
@compileError("Function unsafe for values of bitsize greater than 16.");
}
const fv = @intToFloat(f32, val) / @intToFloat(f32, maxInt(@TypeOf(val))); // make ratio
return @floatToInt(DestType, fv * maxInt(DestType) + 0.5);
}
pub fn main() void {
std.log.info("{}", .{scaleInt(u3, @as(u8, 127))}); // output: 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment