Issue 20535 - std.format: %b, %o, %x and %X on negative integers gives wrong result
Summary: std.format: %b, %o, %x and %X on negative integers gives wrong result
Status: REOPENED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: berni44
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2020-01-26 13:29 UTC by berni44
Modified: 2024-12-01 16:36 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description berni44 2020-01-26 13:29:58 UTC
Currently format casts the value to it's unsigned version and prints that. This is inconsistent with %d. Additionally, if this behaviour is wished, it can easily be accomplished by the user casting himself before formatting.

void main()
{
    import std.format : format;

    assert(format("%b",-17) == "-10001"); // fails
    assert(format("%o",-17) == "-21"); // fails
    assert(format("%x",-17) == "-11"); // fails
    assert(format("%X",-17) == "-11"); // fails
}
Comment 1 Bolpat 2020-12-03 18:54:29 UTC
Reading https://dlang.org/phobos/std_format.html#formattedWrite section 'b','d','o','x','X':
> [...] If the argument is a signed type and the FormatChar is d it is converted to a signed string of characters, otherwise it is treated as unsigned. [...]

So, clearly, the intended result for negative numbers is not a minus sign and magnitude, but two's complement.
Comment 2 Berni44 2021-03-01 19:55:38 UTC
Even, if the current specs state it, this is inconsistent behavior and while it's easy for a user to get the current behavior with a changed implementation it is not possible to get the wished for behavior with the current implementation. So I'm reopening this, but changing to enhancement.
Comment 3 dlangBugzillaToGithub 2024-12-01 16:36:15 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/10404

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB