开发者

What is the VB.NET equivalent of this C# code (convert an ASCII string to hexadecimal)?

What is the VB.NET equivalent of this C# code (convert an ASCII string to hexadecimal)?

public static string AsciiToHex(string asciiString)
{
    string hex = "";

    StringBuilder sBuffer = new StringBuilder();
    for (int i = 0; i < asciiString.Length; i++)
    {
        sBuffer.Append(Convert.ToIn开发者_如何学运维t32(asciiString[i]).ToString("x"));
    }
    hex = sBuffer.ToString().ToUpper();

    return hex;
}


A few things:

  1. Why use a for loop where a foreach look also works? (The answer is: not)
  2. The ToUpper is redundant when we choose the correct formatting flag (X).
  3. The variable hex is useless.
  4. Convert.ToInt32 can be shortened to (int).
  5. The name “ASCII” is actually wrong – you are working with Unicode here.
  6. Usually, this calls for a padding since the ToString("x") result has variable length: for character codes < 16 it yields a single character!

This leaves us with:

public static string CharToHex(string str) {
    StringBuilder buffer = new StringBuilder();
    foreach (char c in str)
        buffer.AppendFormat("{0:X2}", (int) c);
    return buffer.ToString();
}

… and translated into 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


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

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

Which is one of many tools that can do C# to VB conversions, and can by found using this search: http://www.bing.com/search?q=c%23+to+vb+converter&src=IE-SearchBox&FORM=IE8SRC


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜