Skip to content

Commit 0dd38c2

Browse files
committed
std.fmt.hex: support more integer sizes
Fixes ziglang#23799
1 parent a14352b commit 0dd38c2

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

lib/std/fmt.zig

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2758,11 +2758,11 @@ pub const hex_charset = "0123456789abcdef";
27582758

27592759
/// Converts an unsigned integer of any multiple of u8 to an array of lowercase
27602760
/// hex bytes, little endian.
2761-
pub fn hex(x: anytype) [@sizeOf(@TypeOf(x)) * 2]u8 {
2761+
pub fn hex(x: anytype) [2 * @divExact(@typeInfo(@TypeOf(x)).int.bits, 8)]u8 {
27622762
comptime assert(@typeInfo(@TypeOf(x)).int.signedness == .unsigned);
2763-
var result: [@sizeOf(@TypeOf(x)) * 2]u8 = undefined;
2764-
var i: usize = 0;
2765-
while (i < result.len / 2) : (i += 1) {
2763+
const octet_count = @typeInfo(@TypeOf(x)).int.bits / 8;
2764+
var result: [2 * octet_count]u8 = undefined;
2765+
for (0..octet_count) |i| {
27662766
const byte: u8 = @truncate(x >> @intCast(8 * i));
27672767
result[i * 2 + 0] = hex_charset[byte >> 4];
27682768
result[i * 2 + 1] = hex_charset[byte & 15];
@@ -2771,6 +2771,11 @@ pub fn hex(x: anytype) [@sizeOf(@TypeOf(x)) * 2]u8 {
27712771
}
27722772

27732773
test hex {
2774+
{
2775+
const x = hex(@as(u48, 0x1234_5678_3210));
2776+
try std.testing.expect(x.len == 12);
2777+
try std.testing.expectEqualStrings("103278563412", &x);
2778+
}
27742779
{
27752780
const x = hex(@as(u32, 0xdeadbeef));
27762781
try std.testing.expect(x.len == 8);

0 commit comments

Comments
 (0)