我试图在VB.NET(Visual Studio 2010)中打开一个二进制文件,如下所示:
Dim OpenFile1 As New OpenFileDialog
If (OpenFile1.ShowDialog = System.Windows.Forms.DialogResult.OK And (OpenFile1.FileName.Length > 0)) Then
'do something
End If
但是,如果“做某事”是:
Dim readText As String = File.ReadAllText(OpenFile1.FileName)
MsgBox(readText)
仅第一个字节被转换,第二个字节为00(空),并截断文件的其余部分,标记字符串的结尾,并且仅显示第一个字节F0(ASCII中的≡)。
但如果我这样做:
'convert file to hex string
Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFile1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b)
b.ToString("X2"))
Dim newfile As String
newfile = (String.Join("", hex))
RichTextBox1.Text = newfile
现在,字符串已正确转换为十六进制值。到目前为止一切顺利。
但是,当我尝试使用此方法将字符串转换回ASCII时:
'convert hex string to text and put it into the richtextbox
Dim asciistring As String = ""
For x As Integer = 0 To (newfile.Length - 1) Step 2
Dim k As String = newfile.Substring(x, 2)
asciistring &= System.Convert.ToChar(System.Convert.ToUInt32(k,
16)).ToString()
Next
RichTextBox1.Text = asciistring
同样,仅转换第一个字节。其余的一旦找到00(空),就会被截断。 有办法避免这种情况吗?
答案 0 :(得分:0)
Haven't tested out this code yet, but you can try give this method a try :
Public Shared Function ConvertHex(ByVal hexString As String) As String
Try
Dim ascii As String = String.Empty
For i As Integer = 0 To hexString.Length - 1 Step 2
Dim hs As String = String.Empty
hs = hexString.Substring(i, 2)
Dim decval As UInteger = System.Convert.ToUInt32(hs, 16)
Dim character As Char = System.Convert.ToChar(decval)
ascii += character
Next
Return ascii
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return String.Empty
End Function
When calling the function, just pass your hex
string.