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

Unexpected %x behavior with negative #196

Open
brandonros opened this issue May 19, 2020 · 2 comments
Open

Unexpected %x behavior with negative #196

brandonros opened this issue May 19, 2020 · 2 comments

Comments

@brandonros
Copy link

const {sprintf} = require('sprintf-js') // 1.1.2
> sprintf('%x', -4868)
'ffffecfc'

I would have expected -1304, any recommendations?

@tshinnic
Copy link

'hexadecimal' tends to imply "unsigned values" in programming. As an example reference the first link on searching for "printf format specifiers" says "Unsigned hexadecimal integer". Others say "unsigned int" and the like.

Hexadecimal in code is most often used to represent exact binary values concisely, including binary values that would be interpreted as negative by hardware. Hexadecimal in code is not just another number base.

While there is a '%u' for decimal numbers, to switch between signed and unsigned integer, that's a rare usage. (I've only used it when I wanted a 'bad' negative integer to be really obvious visually) The only variation I've needed for hexadecimal is covered by '%X' (which I use always)

So... sprintf-js is doing exactly the "industry-standard" thing. (I hate that term 😄) Anything else would be surprising.

If you really want signed hexadecimal, some variation on this is needed:

function asSignedHex(v) {
    let s = v < 0 ? '-' : '+'
    v = Math.abs(v)
    return sprintf("%s%0X", s, v)
}

@reviewher
Copy link

The README description is vague but the behavior is consistent with other implementations.

README says:

x — yields an integer as a hexadecimal number (lower-case)

Other specs explicitly say the argument is interpreted as unsigned int:

x — The unsigned argument shall be converted to unsigned hexadecimal format

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants