28 April 2009

Neat Little Programming Trick

Okay, most of you will probably never need to do this, but sometimes it may be useful. Say you need to figure out how many digits make up a number (say for buffering purposes). The simplest way of performing this task would be to print out the number to a string and count the number of characters in the string. Simple, but ultimately not very elegant. So here is a way to do it without using a string at all - and in only 1 line:

int numberLength(int num, int base) {
return ((int)floor(log(num)/log(base)))+1;
}

int len;
len = numberLength(32767, 10); //returns 5
len = numberLength(32767, 2); //returns 15
len = numberLength(32767, 16); //returns 4

All you have to do is call the "numberLength" function, passing the number you want to count the length on (the value must be >= 1), then in the second parameter pass what the base of the number is. In the examples above, passing a value of 10 returns how long it is in decimal (32767 has 5 digits); passing a 2 returns how long it is in binary (32767=0b111111111111111 which is 15 ones); and passing an 16 returns how long the number is in hex (32767=0x7FFF which is 4 hex characters). How does it work? Well, lets think of a number like this: every number of base 10 (standard decimal numbers) can be written as this: 1234 = 1.234*10^3 or 987654 = 9.87654*10^5. Thus, we can safely ignore the number and look at the 10^x part, using the log function to retrieve the exponenent x. However, this is off by 1, therefore we get the +1 tacked on. We floor the log, though, since we do not want the actual log, just the integer-part. Now, like I said, this will only work for values greater than or equal to 1, and that's just because we rely on the log function, but this is easy to work around, as we could enhance the function:

int numberLength(int num, int base) {
return (num == 0 ? 1 : ((int)floor(log(num)/log(base)))+1);
}

int len;
len = numberLength(32767, 10); //returns 5
len = numberLength(32767, 2); //returns 15
len = numberLength(32767, 16); //returns 4
len = numberLength(0, 10); //returns 1
len = numberLength(0, 2); returns 1
len = numberLength(0, 16); returns 1

Tada! That's it! Isn't this cool?! Okay, enough nerdiness. Back to work!

1 comment:

AJ said...

i remember in college one of the very first programs we had to write in the beginner CS class was a change machine. I think I used a similar function but then the TA told me to divide by 10 each time so that we got the hang of floating points. LOLz