Powers of two are second nature to a lot of programmers. They're nearly inescapable.

Equally inescapable are programmers finding new ways to do simple things wrong. Take Sander's co-worker, who needed to figure out, given a number of bits, what's the largest possible value you could store in that number of bits. You or I might reach for our language's pow function, but boy, in C++, that might mean you need to add an include file, and that sounds hard, so let's do this instead:

DWORD CBitOps::BitPower(WORD wNrOfBits) { DWORD Res = 1; if (wNrOfBits == 0) { return true; } for (WORD counter = 0; counter < wNrOfBits; counter++) { Res = Res*2; } return Res; }

Indenting as submitted, just for that extra little something.

The bit that puzzles me is that it wisely validates its inputs… but it returns true if you passed in a zero. And arguably, the input validation is incomplete, as a large value in wNrOfBits could easily create an output much larger than DWORD can hold. Still, the return true is going to cast a boolean to a DWORD which because this is clearly WinAPI code, I'm sure it's going to do something weird like actually return 0, which raises the question: why not return 0 in that case?

Sander did the "hard" work of throwing this code away and replacing it with a more standard call to the math libraries.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!