-1

So I am migrating some code from VB.NET to C# however it fails when it is doing a byte parse in C#.

here is the VB.NET code would works:

Dim sModifiedAccountNumber_AsciiHex
Dim iByte As Byte = 0
Dim iIdx As Integer = 0
Dim strByte As String = String.Empty

sModifiedAccountNumber_AsciiHex = "FC13"
For iIdx = 1 To 3 Step 2

    iByte = CByte("&H" & Mid$(sModifiedAccountNumber_AsciiHex, iIdx, 2))
    If iByte >= 120 And iByte <= 127 Then
        iByte = iByte Or &H80
        strByte = Hex$(iByte)
        Do While Len(strByte) < 2
            strByte = "0" & strByte
        Loop
        Mid$(sModifiedAccountNumber_AsciiHex, iIdx, 2) = strByte
    End If

Next

The C# version:

string modAccountNumberAsciiHex = "FC13";
byte iByte;
string strByte = string.Empty;

for (int iIdx = 1; iIdx <= 3; iIdx += 2)
{
    iByte = byte.Parse(("&H" + modAccountNumberAsciiHex.Substring((iIdx - 1), 2)));
    if (iByte >= 120 && iByte <= 127)
    {
        iByte = iByte |= 0x80;
        strByte = BitConverter.ToString(new byte[] { iByte });
        while (strByte.Length < 2)
        {
            strByte = "0" + strByte;
        }

        // TODO: convert the line below to C#   
        // Mid$(sModifiedAccountNumber_AsciiHex, iIdx, 2) = strByte

    }
}

so in C# I always get a FormatException when doing the byte.Parse (line straight after the for statement)

Any thoughts on what this should be in C#?

In addition - the C# version in the TODO comment would also be appreciated :-)

GSerg
  • 76,472
  • 17
  • 159
  • 346
Ahmed ilyas
  • 5,722
  • 8
  • 44
  • 72

2 Answers2

5

The mistake is including the "&H" at the start of the string, and using byte.Parse without specifying NumberStyles.AllowHexSpecifier. It would be simpler to use Convert.ToByte though:

 byte x = Convert.ToByte(modAccountNumberAsciiHex.Substring(iIdx - 1, 2), 16)

Also note that your code is currently very "1-based". It feels like ported VB. More idiomatic C# would be:

for (int index = 0; index < 3; index += 2)
{
    byte x = Convert.ToByte(text.Substring(index, 2), 16);
    ...
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon. you are right, it IS VB6 code. and yes im aware of the &H. it works when I do the following: iByte = byte.Parse(modAccountNumberAsciiHex.Substring((iIdx - 1), 2), System.Globalization.NumberStyles.HexNumber);. – Ahmed ilyas Jul 21 '12 at 15:23
1

You don't need to include the "&H" in C#:

byte.Parse((modAccountNumberAsciiHex.Substring((iIdx - 1), 2)));
goric
  • 11,491
  • 7
  • 53
  • 69