Parsing string to integer accepting '0x' + hexadecimal
Nobody has claimed this yet.
- Dominant language
- Markdown
- Stars
- 6.6k
- Forks
- 1.7k
- Avg merge
- 16h 14m
- Merged PRs (30d)
- 1
Description
In many cases, it is useful for a program that parses integers (e.g. from the command line) to accept both decimal and hexadecimal constants, by letting the user prefix the latter with 0x. Currently, FromStr::from_str (also the destination of str::parse) only accepts base 10; from_str_radix allows an arbitrary base to be specified, but doesn't have any special magic to parse prefixes.
If I were writing from_str from scratch, I would suggest having it accept 0x, perhaps along with 0o and 0b like Rust source, because even if many applications don't have any particular reason to expect hexadecimal, there's very little advantage to rejecting it*. At this point, I guess that would be something of a breaking change, so a new method would be needed; still, I claim such a method belongs in the standard library for the same reason. Alternatively, from_str_radix could accept radix 0 like some other languages' equivalents, although this seems like a hack.
Other languages' behavior:
- C
atoionly accepts base 10. - The C
strtolfamily has a mandatory base parameter; base=0 is decimal by default but allows0xand0755(octal); base=16 accepts0x - Python
int()is base 10 only by default, but has a base parameter; same behavior as C except0band0oare also accepted - Ruby:
'0x123'.to_iis 0, butInteger('0x123')is 291. I have no idea. The latter seems to accept the same as Python. - JavaScript:
parseIntby default accepts0xand, in some browsers,0-for-octal, which ES5 says not to.
(I certainly don't propose interpreting leading zeroes as octal.)
- One possible reason to reject alternate forms would be to give each integer a unique input representation, but of course
-0and0, and008and8parse to the same value.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the discussion around FromStr::from_str, str::parse, and from_str_radix in this issue, including the examples from other languages. Done would require a settled API design and documented behavior for hexadecimal prefixes, rather than a localized implementation or named test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100