Gopher2011
Gopher2011

Reputation: 179

Conversion vb6 to c#

I am trying to convert some vb6 code to c# and I am struggling a bit. I have looked at this page below and others similar, but am still stumped.

Why use hex?

vb6 code below:

    Dim Cal As String
    Cal = vbNull

    For i = 1 To 8
        Cal = Cal + Hex(Xor1 Xor Xor2)
    Next i

This is my c# code - it still has some errors.

        string Cal = null;
        int Xor1 = 0;
        int Xor2 = 0;

        for (i = 1; i <= 8; i++)
            {
            Cal = Cal + Convert.Hex(Xor1 ^ Xor2);
            }

The errors are:

        Cal = Cal + Convert.Hex(Xor1 ^ Xor2 ^ 6);

Any advice as to why I cant get the hex to convert would be appreciated. I suspect its my lack of understanding the .Hex on line 3 above and the "&H" on line 1/2 above.

Upvotes: 2

Views: 2978

Answers (1)

Heinzi
Heinzi

Reputation: 172200

Note: This answer was written at a point where the lines Xor1 = CDec("&H" + Mid(SN1, i, 1)) and Xor1 = Convert.ToDecimal("&H" + SN1.Substring(i, 1)); were still present in the question.


What's the &H?

In Visual Basic (old VB6 and also VB.NET), hexadecimal constants can be used by prefixing them with &H. E.g., myValue = &H20 would assign the value 32 to the variable myValue. Due to this convention, the conversion functions of VB6 also accepted this notation. For example, CInt("20") returned the integer 20, and CInt("&H20") returned the integer 32.

Your code example uses CDec to convert the value to the data type Decimal (actually, to the Decimal subtype of Variant) and then assigns the result to an integer, causing an implicit conversion. This is actually not necessary, using CInt would be correct. Apparently, the VB6 code was written by someone who did not understand that (a) the Decimal data type and (b) representing a number in decimal notation are two completely different things.


So, how do I convert between strings in hexadecimal notation and number data types in C#?

To convert a hexadecimal string into a number use

int number = Convert.ToInt32(hex, 16);   // use this instead of Convert.ToDecimal

In C#, there's no need to pad the value with "&H" in the beginning. The second parameter,16, tells the conversion function that the value is in base 16 (i.e., hexadecimal).

On the other hand, to convert a number into its hex representation, use

string hex = number.ToString("X");       // use this instead of Convert.ToHex

What you are using, Convert.ToDecimal, does something completely different: It converts a value into the decimal data type, which is a special data type used for floating-point numbers with decimal precision. That's not what you need. Your other method, Convert.Hex simply does not exist.

Upvotes: 9

Related Questions