Hakusa@[EMAIL PROTECTED]
<Hakusa@[EMAIL PROTECTED]
> wrote:
> unsigned int getHexDigit( unsigned int hex, unsigned short
> digitWanted )
> {
> // Tricky calculation, but it basically creates a mask (0xf) and
> ****fts it
> // over until it's at the desired digit (keeping in mind the size
> of an int
> // is 4). Then, the resault is ****fted back to the ones place.
> // The digit wanted is subtracted by 1 because the one's place is
> // already where it's at.
> return ( hex & 0xf << (digitWanted-1) * 4 ) >> (digitWanted-1) * 4;
Two (related) stylistic points here:
First, I would suggest some extra parentheses to make the operator-
-preceence parsing unambiguous here: did you mean to return
((hex&0xf) << ((digitWanted-1)*4)) >> ((digitWanted-1)*4);
or
(hex&0xf) << (((digitWanted-1)*4) >> ((digitWanted-1)*4));
or
hex & ( ((0xf << (digitWanted-1)) * 4) >> ((digitWanted-1) * 4) );
or any of a whole bunch of other "possible" parses? (Of course, the
C++ programming language precisely defines how the original expression
is parsed... but even if *you* know what you meant, another programmer
who has to look at this code in the future might not be so sure.)
Second, the difficulty of parsing this, and the number of nested
parentheses involved, suggests maybe introducing a tem****ary variable:
unsigned int ****ftDistance = (digitWanted-1) * 4;
return (hex & (0xf << ****ftDistance)) >> ****ftDistance;
I think this is a lot easier to read and less error-prone.
ciao,
--
-- From: "Jonathan Thornburg [remove -animal to reply]"
<J.Thornburg@[EMAIL PROTECTED]
>
School of Mathematics, U of Southampton, England
"C++ is to programming as *** is to reproduction. Better ways might
technically exist but they're not nearly as much fun." -- Nikolai
Irgens
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|