authorgravatar for richard@levitte.orgRichard Levitte <richard@levitte.org> 2026-04-16 04:53:07+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-04-16 19:44:40+02:00
logffcfeb919fc08724eea0346af8ea5531d62e2734
treeaf9df66bcd81556c6aa78ab37bb0be5b5000a5fd
parent29532177c1c03a20d011e794f9abb70f1bdb6d59

Fix std.fmt.hex() to work with unsigned ints of all multiples of 8 bits

@SizeOf(@typeInfo(T)) for any u{n} seems to give sizes of u32, u64, u128 and so on, depending on what size x fits into. This causes problems with '>>' if x isn't exactly one of those sizes. @typeInfo(@TypeOf(x)).int.bits gives a more accurate size.

1 files changed, 7 insertions(+), 2 deletions(-)

lib/std/fmt.zig+7-2
...@@ -1342,9 +1342,9 @@ pub const hex_charset = "0123456789abcdef";...@@ -1342,9 +1342,9 @@ pub const hex_charset = "0123456789abcdef";
13421342
1343/// Converts an unsigned integer of any multiple of u8 to an array of lowercase1343/// Converts an unsigned integer of any multiple of u8 to an array of lowercase
1344/// hex bytes, little endian.1344/// hex bytes, little endian.
1345pub fn hex(x: anytype) [@sizeOf(@TypeOf(x)) * 2]u8 {1345pub fn hex(x: anytype) [@typeInfo(@TypeOf(x)).int.bits / 4]u8 {
1346 comptime assert(@typeInfo(@TypeOf(x)).int.signedness == .unsigned);1346 comptime assert(@typeInfo(@TypeOf(x)).int.signedness == .unsigned);
1347 var result: [@sizeOf(@TypeOf(x)) * 2]u8 = undefined;1347 var result: [@typeInfo(@TypeOf(x)).int.bits / 4]u8 = undefined;
1348 var i: usize = 0;1348 var i: usize = 0;
1349 while (i < result.len / 2) : (i += 1) {1349 while (i < result.len / 2) : (i += 1) {
1350 const byte: u8 = @truncate(x >> @intCast(8 * i));1350 const byte: u8 = @truncate(x >> @intCast(8 * i));
...@@ -1360,6 +1360,11 @@ test hex {...@@ -1360,6 +1360,11 @@ test hex {
1360 try std.testing.expect(x.len == 8);1360 try std.testing.expect(x.len == 8);
1361 try std.testing.expectEqualStrings("efbeadde", &x);1361 try std.testing.expectEqualStrings("efbeadde", &x);
1362 }1362 }
1363 {
1364 const s = "[" ++ hex(@as(u48, 0x12345678_abcd)) ++ "]";
1365 try std.testing.expect(s.len == 14);
1366 try std.testing.expectEqualStrings("[cdab78563412]", s);
1367 }
1363 {1368 {
1364 const s = "[" ++ hex(@as(u64, 0x12345678_abcdef00)) ++ "]";1369 const s = "[" ++ hex(@as(u64, 0x12345678_abcdef00)) ++ "]";
1365 try std.testing.expect(s.len == 18);1370 try std.testing.expect(s.len == 18);