Skip to content

std.fmt.hex does not work for integers that are not powers of two #23799

Open
@Noodlez1232

Description

@Noodlez1232

Zig Version

0.14.0

Steps to Reproduce and Observed Behavior

Write a test.zig

const std = @import("std");
test "hex" {
    std.debug.assert(48 % 8 == 0); // multiple of u8
    const hex = std.fmt.hex(@as(u48, 0x1234_5678_3210));
    try std.testing.expectEqual(hex.len, 12);
    try std.testing.expectEqualStrings("123456783210", &hex);
}

run zig test test.zig

Get error:

thread 21610 panic: shift amount is greater than the type size
/nix/store/figbx3530fg8m6b1mfd9mvd9cpc141z3-zig-0.14.0/lib/zig/std/fmt.zig:2770:38: 0x104a88d in hex__anon_409 (test)
        const byte: u8 = @truncate(x >> @intCast(8 * i));
                                     ^
/home/nathaniel/Misc/Programs/test.zig:3:28: 0x104a681 in test.hex (test)
    const hex = std.fmt.hex(@as(u48, 0x1234_5678_3210));
                           ^
/nix/store/figbx3530fg8m6b1mfd9mvd9cpc141z3-zig-0.14.0/lib/zig/compiler/test_runner.zig:214:25: 0x10f2829 in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/nix/store/figbx3530fg8m6b1mfd9mvd9cpc141z3-zig-0.14.0/lib/zig/compiler/test_runner.zig:62:28: 0x10ead7d in main (test)
        return mainTerminal();
                           ^
/nix/store/figbx3530fg8m6b1mfd9mvd9cpc141z3-zig-0.14.0/lib/zig/std/start.zig:647:22: 0x10ea302 in posixCallMainAndExit (test)
            root.main();
                     ^
/nix/store/figbx3530fg8m6b1mfd9mvd9cpc141z3-zig-0.14.0/lib/zig/std/start.zig:271:5: 0x10e9edd in _start (test)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x0 in ??? (???)

Expected Behavior

Test passes as is listed in the std documentation (since it is a multiple of u8).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions