Article 6BVTT CodeSOD: Counting Digits

CodeSOD: Counting Digits

by
Remy Porter
from The Daily WTF on (#6BVTT)

Denise was supervising a developer who encountered a difficult problem: string handling in C. It's not particularly fun to work with strings in C, but it's certainly feasible.

One of the key issues for strings is that you need to know how large the string is going to be so you can allocate a buffer for it. And while there's a strlen, there is no intlen, so when you want to turn a number into a string, you're faced with a branching path.

The first path, would be to simply remember your logarithms from high school and know that the log10 of a number tells you how many digits (in base 10) it holds.

The second path would be to learn how to use the printf family of functions, and let the C standard solve that problem for you.

The third path would be to do this:

unsigned int digits_count(unsigned int x) { //unsigned int ret = 1; if (x >= 100000000) return 9; if (x >= 10000000) return 8; if (x >= 1000000) return 7; if (x >= 100000) return 6; if (x >= 10000) return 5; if (x >= 1000) return 4; if (x >= 100) return 3; if (x >= 10) return 2; return 1;}

So here we have a TDWTF classic: a useless function that reinvents a wheel which didn't need reinventing in the first place. But it has a bonus of also being wrong.

The largest value in an unsigned int on this platform is 4,294,967,295, which has 10 digits. This function would helpfully tell you that it only has 9 digits, introducing a fun little off by one error that I'm sure won't surprise anybody in ugly ways at some point.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments