这个C#代码的VB.NET等价物是什么(将ASCII字符串转换为十六进制)?
public static string AsciiToHex(string asciiString)
{
string hex = "";
StringBuilder sBuffer = new StringBuilder();
for (int i = 0; i < asciiString.Length; i++)
{
sBuffer.Append(Convert.ToInt32(asciiString[i]).ToString("x"));
}
hex = sBuffer.ToString().ToUpper();
return hex;
}
答案 0 :(得分:5)
一些事情:
for
循环,其中foreach
看起来也有效? (答案是:不是)ToUpper
)时X
是多余的。hex
无用。Convert.ToInt32
可缩短为(int)
。ToString("x")
结果具有可变长度:对于字符代码&lt; 16它产生一个字符!这给我们留下了:
public static string CharToHex(string str) {
StringBuilder buffer = new StringBuilder();
foreach (char c in str)
buffer.AppendFormat("{0:X2}", (int) c);
return buffer.ToString();
}
...并翻译成VB:
Public Shared Function CharToHex(ByVal str As String) As String
Dim buffer As New StringBuilder()
For Each c As Char in str
buffer.AppendFormat("{0:X2}", Asc(c))
End For
Return buffer.ToString()
End Function
答案 1 :(得分:4)
Public Shared Function AsciiToHex(asciiString As String) As String
Dim hex As String = ""
Dim sBuffer As New StringBuilder()
For i As Integer = 0 To asciiString.Length - 1
sBuffer.Append(Convert.ToInt32(asciiString(i)).ToString("x"))
Next
hex = sBuffer.ToString().ToUpper()
Return hex
End Function
通过http://www.developerfusion.com/tools/convert/csharp-to-vb/
这是可以执行C#到VB转换的众多工具之一,可以使用此搜索找到:http://www.bing.com/search?q=c%23+to+vb+converter&src=IE-SearchBox&FORM=IE8SRC
答案 2 :(得分:2)
Public Shared Function AsciiToHex(asciiString As String) As String
Dim hex As String = ""
Dim sBuffer As New StringBuilder()
For i As Integer = 0 To asciiString.Length - 1
sBuffer.Append(Convert.ToInt32(asciiString(i)).ToString("x"))
Next
hex = sBuffer.ToString().ToUpper()
Return hex
End Function