-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Implementations of formatting traits for signed integers can be ambiguous #42860
Comments
This representation dates back to #1653 which implemented UpperHex using For what it's worth, #include <iostream>
int main() {
int32_t x = -15;
std::cout << std::uppercase << std::hex << x << '\n';
} #include <stdint.h>
#include <stdio.h>
int main(void) {
int32_t x = -15;
printf("%X\n", x);
} I don't believe we need to change the behavior but I do agree that the expectations around implementation of UpperHex and friends needs to be documented better. |
Your code in C invoke undefined behavior, |
Thanks @Stargateur. What would be the defined way to print a signed 32-bit integer in uppercase hex? |
There are no way,
Like you see, standard don't give any specifier to print an #include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
int main(void) {
int32_t x = -15;
printf("%"PRIX32"\n", (uint32_t)x);
} Overflow of unsigned integer are defined by C standard so the cast is not undefined. AFAIK |
I think this was addressed by #46285 |
@Phlosioneer That is correct! :) Closing. |
I was recently formatting a signed integer primitive to hexadecimal using the standard formatter API, hoping that the result would be aware of the value's sign. It turns out that the implementations of
UpperHex
(and relatives such asLowerHex
andBinary
) for signed integers simply treat these numbers as unsigned (or just a sequence of bits).I posted this concern first as an SO question. A way around this is to make a newtype with another formatting implementation.
I can make arguments on both sides whether it should (or not) behave like this, but what actually concerns me most is that there seems to be no mention of this behaviour in the documentation. It appears that formatting trait implementations do not have to abide to a value's sign, but then the fact that a negative integer is treated as an unsigned number for formatting purposes can be unexpected for some people, especially when the docs do not clarify this situation.
To sum up: should we improve the documentation regarding what makes a valid formatting trait implementation? Should we also (or just) document further their implementations for integers in particular? I am willing to collaborate with the necessary changes one we're clear about what should be improved.
The text was updated successfully, but these errors were encountered: