Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.format: %b, %o, %x and %X on negative integers gives wrong result #10404

Open
dlangBugzillaToGithub opened this issue Jan 26, 2020 · 2 comments

Comments

@dlangBugzillaToGithub
Copy link

bugzilla (@berni44) reported this on 2020-01-26T13:29:58Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=20535

CC List

Description

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
}
@dlangBugzillaToGithub
Copy link
Author

qs.il.paperinik commented on 2020-12-03T18:54:29Z

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.

@dlangBugzillaToGithub
Copy link
Author

bugzilla (@WalterBright) commented on 2021-03-01T19:55:38Z

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.

@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants