Skip to content

Instantly share code, notes, and snippets.

@Justasic
Last active October 15, 2018 02:22
Show Gist options
  • Save Justasic/593cb2ba2934933fba63b0e927bda3a6 to your computer and use it in GitHub Desktop.
Save Justasic/593cb2ba2934933fba63b0e927bda3a6 to your computer and use it in GitHub Desktop.
Just a simple character to integer conversion function with bounds checking
template<typename T> T safeatoi(const char *buffer, size_t len)
{
T returnval = 0;
// parse each char and get the int value.
for (size_t i = 0; i < len; ++i)
{
char ch = buffer[i];
T value = ch - '0';
if (value >= 0 && value <= 9)
returnval = returnval * 10 + value;
}
return returnval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment