3 ms·
Like 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
by Sharlin 3y ago
Like 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