I have some code that involves parsing incoming serial data and then converting it to numbers.
The incoming data should be a set of coma separated integers (and normally is unless there's some corruption during transmission)
I can split the incoming data into strings (i.e. an array of characters) and then convert it using atoi()
If the string really is an integer i.e. "12345" then atoi() will correctly convert this to an int of value 12345. If the string represents something larger than an int i.e. "99999" then atoi() won't work correctly.
Is there any way of testing the string before using atoi() (something like isNumeric() or isInteger()). There are three issues here, firstly atoi() won't give me the correct value if the string is too large to be an integer, secondly it won't generate an error to warn me, and finally it will (I think) generate an overflow with may corrupt some other data.
What I've done so far is to test the length of my string, if its 5 characters long then I convert the left most two into a number and check it's lower than 32. If it's is then the string must be an integer, but there must be a simplier/more elegant way?
I have tried that and it does work, but it's not the best solution. It uses double the memory (I'm processing a lot of fields) and it doesn't actually prevent the problem it just reduces the odds of it happening.
It'll only use twice the memory for a single variable - after that, you can decide whether or not the value is too big for an int or not and act appropriately.
Otherwise, a simple parser.
It'll only use twice the memory for a single variable - after that, you can decide whether or not the value is too big for an int or not and act appropriately.
Just write your own IsInteger function and parse the string yourself. Use a long to accumulate the number and return false if it gets too big. To be slightly more efficient, pass a reference to the integer variable you're trying to populate and set it if the parsed result is within int limits.
OP said that that only reduces the possibility of the issue. I'm assuming that means that corrupted communications may produce a stream of digits that is too big for atol to handle.