简体   繁体   中英

Works in VB.NET but not in C# - byte conversion

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 :-)

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);
    ...
}

您无需在C#中包含“&H”:

byte.Parse((modAccountNumberAsciiHex.Substring((iIdx - 1), 2)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM