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:
- Why use a
for
loop where aforeach
look also works? (The answer is: not) - The
ToUpper
is redundant when we choose the correct formatting flag (X
). - The variable
hex
is useless. Convert.ToInt32
can be shortened to(int)
.- The name “ASCII” is actually wrong – you are working with Unicode here.
- 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/
精彩评论