[Mono-devel-list] Re: Can you help me in this conversion from VB to C# ?

Jonathan Gilbert 2a5gjx302 at sneakemail.com
Wed Sep 22 03:06:39 EDT 2004

At 10:28 PM 21/09/2004 -0700, you wrote:
>Alessandro Torrisi wrote:
>> public static string LockToKey(string Lock) {
>>   string LockToKey;
>>   --snip--
>>   return LockToKey;
>>  }
>not going through the whole thing, but your private variable is named the
>same as the function it belongs to, not sure if this is allowed, but just
>seems like bad karma programming wise.  best bet is to use a variable that
>is at least something else.. I tend to use "ret" as a variable name to
>hold the return value... ymmv, and may not be the best either, but is at
>least safer...  Lock, although not "lock" (iirc, a keyword)..
>   while (h>255) {
>    h = h - 256;
>   }
>umn, I think this would be better to use a modulus...
>h = (h > 255)?(h%255):h;
>if h is greater than 255, it assigns the modulus operator, otherwise
>it re-assigns h, although...
>if (h > 255) h = h%255;
>may be better still... but the compiler should handle this in either case.

Both of these are wrong, and neither of them are "good style".

The reason they are wrong is that the original loop takes the remainder of
a division by 256; your modulus operations use a divisor of 255, which will
yield wildly incorrect results.

The appropriate way to implement this is simply:

h %= 256;

The division involved only takes a handful of clock cycles on modern
processors, and certainly a conditional operation will involve a branch of
some sort, and you want to avoid that.

If you don't mind sacrificing a small amount of readability, you can same
those division cycles by using a bitwise AND operation. This only works for
powers of two, but the above could be written as:

h &= 255;

Note that this value is one less than the power of two, while the divisor
for the '%' operatior is the power of two itself.

It should also be noted that when negative values are involved, neither of
these "replacements" duplicates the behaviour of the original loop. I
haven't looked at the full code, so I don't know if this is an issue, but,
for example:

-257 % 256 == -1
-257 & 255 == +255

When passed through the original loop, however, -257 is unchanged (since it
is never larger than 255, the condition to enter the loop in the first place).


More information about the Mono-devel-list mailing list