The most performant version of the code I could come up with is below, it should be about 10x faster than using log
. You can also see @Aetol's solution here which is the simplest fast solution I think.
// Boundaries of 2^x that cross 10^y: 4, 7, 10, 14, 17, 20, 24, 27, 30
inline unsigned int getLengthOfInt (int n)
{
if (n >> 3 == 0) {
return (n >= 10) ? 2 : 1;
} else if (n >> 6 == 0) {
return (n >= 100) ? 3 : 2;
} else if (n >> 9 == 0){
return (n >= 1000) ? 4 : 3;
} else if (n >> 13 == 0){
return (n >= 10000) ? 5 : 4;
} else if (n >> 16 == 0){
return (n >= 100000) ? 6 : 5;
} else if (n >> 19 == 0){
return (n >= 1000000) ? 7 : 6;
} else if (n >> 23 == 0){
return (n >= 10000000) ? 8 : 7;
} else if (n >> 26 == 0){
return (n >= 100000000) ? 9 : 8;
} else if (n >> 29 == 0){
return (n >= 1000000000) ? 10 : 9;
}
return 10; // limited by int size
}