Created
February 23, 2021 23:50
-
-
Save lukewilson2002/83b5cb93849f20c36c43d12e0d77e576 to your computer and use it in GitHub Desktop.
Scale integers from of larger size to integers of a smaller size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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