Question

I'm experiencing a bit of an issue while trying to convert some VB6 logic into C#. In one of the VB6 functions, it has the following statement:

w = Not CByte(w)

Where w is a long.

In an example, after this line evaluates in VB6, I can see the following change:
Before: w = 110
After: w = 145

However, in C#, I've rewritten the method to contain the following code:

w = ~(byte)w;

But, when I run the same example, I get these results, instead:
Before: w = 110
After: w = -111

I also get the same result doing:

w = ~(Convert.ToByte(w));

I was finally able to get the correct results with the following change:

w = ~(byte)w & 0xFF;

From what I can tell, it looks like C# is converting it to an sbyte even though it's not specified to do so. My question is: is there some flaw in my logic? Is this the only way to get the VB6 equivalent?

Was it helpful?

Solution

w is a long, but let's say it's an int, it doesn't really matter except it's slightly easier to explain.

w = ~(byte)w;

Ok, so w is cast to a byte .. and then immediately back to int because that's what arithmetic operations do.

You could solve it by taking Justin's suggestion from the comments (which does the cast at the right moment: (byte)~w), or with this:

w ^= 0xFF;

That is not strictly the same thing though, it's different if w starts out with a value outside of the range of a byte.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top