4 ms·
I tried this out but it parsed the string "123\n" as 32. Also it parses "400" as 144, when the reference implementation considers it not-a-uint8, but I don't m
by jstanley 3y ago
I tried this out but it parsed the string "123\n" as 32.
Also it parses "400" as 144, when the reference implementation considers it not-a-uint8, but I don't mind so much about that.
EDIT: Ah, I think it assumes the string contains only a uint8, rather than trying to parse a uint8 from the start of a string. So you need to zero out the "\n" separately, and then it works.
- Sharlin 3y agoLike the article says, it uses SWAR and requires a buffer of at least four bytes, with the trailing bytes zeroed. Your strings were both four bytes which saved you; had you tried with "42" or something, that would've been undefined behavior! Edit: No, wait, the `len` parameter is there to ensure that trailing bytes don't matter. But note that it must be the length of the number-containing prefix part, not the whole input string! > Also it parses "400" as 144 Did you check the return value? If false (as it is in case of overflow), the result is meaningless.
- jstanley 3y agoYes I checked the return value. Example using the program from https://news.ycombinator.com/item?id=38451560 https://news.ycombinator.com/item?id=38451560 $ ./parse256 400 value of 400 is 144
- tom_ 3y ago400 is not an 8-bit integer! This function appears to be for parsing integers you know in advance will fit into 8 bits, rather than arbitrary input.
- jstanley 3y ago> The function returns a Boolean value indicating whether the input string can be parsed into an unsigned 8-bit integer or not. It returns 1 even though 400 is too large.
- tom_ 3y agoBut the parsed value was 144. It's less than 256! It fits! Indeed, all 3 conditions for returning true were satisfied. Just goes to show the value of accurate documentation: (Always safest to trust the docs. The code could easily be wrong!) - string is 3 chars or less - string contains no non-digit chars - parsed value is less than 256