atoi
a_riot42
Posts: 1,624
atoi is supposed to return the integer representation of the string it is sent. If no valid characters are found, it returns 0. But what if you send it '0'? Won't it also return 0? I wanted to use atoi to check to see if the string I am receiving is a valid number but 0 is a possibility so if I check atoi's return value, if could be a valid number yet still return 0.
Paul
Paul
0
Comments
$30 is 0 so they are equivalent so checking it won't do any good. The above code looks like it will work though. I went a different route and took advantage of the fact that for 0, I get 00, since the field is two digits wide. So I did it this more convoluted way instead:
but in the case where I would get 0 instead of 00, the above method looks like the best way. Thanks for the suggestion, that's a clever way of doing it. I've used itoa(atoi()) in the past for certain situations but didn't think of it here.
Paul
so if, for example, the original string was 'Z' you get atoi('Z')=0 But the hex value of the string 'Z' is $5A, not $30.
I like this idea in that the other suggestions involve more than one evaluating process no matter what the parsing result is. This one only kicks in when there's a zero. Otherwise, you just do the atoi and move on with your life.
Oh, my mistake. Yes that should work. I thought you meant comparing it after atoi(). Is this what you meant?
Paul
I'll have to look over some older code and see if I have used atoi carelessly and not realized I might be getting a valid integer of zero but thought I got a non digit instead. In many cases it won't make a difference to the outcome but in some it could. I came across this issue tracking Denon volume for the second zone. The response to a change in volume of the second zone is Z280, but all the other second zone responses also start with Z2, like Z2CD, Z2MU, etc. The only way to determine if you are getting a volume response is to check if the characters after the 'Z2' are a number. In this particular case, if atoi returns 0 because the response had no number, then the volume feedback would get set to 0, which should only happen when atoi returns a 0 because it was passed a '0'. Isn't programming fun?
Paul
Since ATOI will go through a whole char array looking for a numeric sequence, than convert just that numeric sequence. You can use this method to check if there is a numeric sequence in the char array.
'Hello123Today456'
Atoi will return 123.