什么是这个C#代码的VB.NET等价物(将ASCII字符串转换为十六进制)?

时间:2011-01-03 21:23:34

标签: c# vb.net c#-to-vb.net

这个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;
}

3 个答案:

答案 0 :(得分:5)

一些事情:

  1. 为什么使用for循环,其中foreach看起来也有效? (答案是:不是)
  2. 当我们选择正确的格式标记(ToUpper)时X是多余的。
  3. 变量hex无用。
  4. Convert.ToInt32可缩短为(int)
  5. 名称“ASCII”实际上是错误的 - 您在这里使用Unicode。
  6. 通常,这需要填充,因为ToString("x")结果具有可变长度:对于字符代码&lt; 16它产生一个字符!
  7. 这给我们留下了:

    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

http://www.developerfusion.com/tools/convert/csharp-to-vb/