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.
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.
Note: This answer was written at a point where the lines
Xor1 = CDec("&H" + Mid(SN1, i, 1))
andXor1 = 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 = &H20would assign the value32to the variablemyValue. Due to this convention, the conversion functions of VB6 also accepted this notation. For example,CInt("20")returned the integer20, andCInt("&H20")returned the integer32.Your code example uses
CDecto convert the value to the data typeDecimal(actually, to the Decimal subtype ofVariant) and then assigns the result to an integer, causing an implicit conversion. This is actually not necessary, usingCIntwould be correct. Apparently, the VB6 code was written by someone who did not understand that (a) theDecimaldata 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
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
What you are using,
Convert.ToDecimal, does something completely different: It converts a value into thedecimaldata 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.Hexsimply does not exist.