Be careful, this code assumes that there is at least one digit in the buffer. To make it work with empty buffer too:
uint32_t result = 0;
for (int i = 0; i < len; i++) {
result *= 10;
result += buffer[i] - '0';
}
return result;
In terms of performance, I don't think it's possible to achieve better using clean techniques. There are some optimizations that might help performance, but hurt readability and maintainability. For example you could try loop unrolling:
if (len == 0) return 0;
if (len == 1) {
return buffer[0] - '0';
}
if (len == 2) {
return (buffer[0] - '0') * 10 + buffer[1] - '0';
}
// ... and so on, until the max supported length
Yes it's ugly. But loop unrolling tends to improve performance. Tends, the result may depend on your compiler, platform, or the weather. You'll have to measure performance before and after to see if this optimization actually helps our not.