[英]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#. 因此,我正在将某些代码从VB.NET迁移到C#,但是当它在C#中执行字节解析时,它将失败。
here is the VB.NET code would works: 这是VB.NET代码可以使用的代码:
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: C#版本:
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) 所以在C#中,执行byte.Parse
(for语句后的直线)时总是会收到FormatException
Any thoughts on what this should be in C#? 关于在C#中应该有什么想法?
In addition - the C# version in the TODO comment would also be appreciated :-) 另外-TODO注释中的C#版本也将不胜感激:-)
The mistake is including the "&H" at the start of the string, and using byte.Parse
without specifying NumberStyles.AllowHexSpecifier
. 错误是在字符串的开头包含“&H”, 并使用byte.Parse
而不指定NumberStyles.AllowHexSpecifier
。 It would be simpler to use Convert.ToByte
though: 使用Convert.ToByte
会更简单:
byte x = Convert.ToByte(modAccountNumberAsciiHex.Substring(iIdx - 1, 2), 16)
Also note that your code is currently very "1-based". 另请注意,您的代码当前非常基于“ 1”。 It feels like ported VB. 感觉就像移植了VB。 More idiomatic C# would be: 更惯用的C#将是:
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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.