字符串为十六进制和十六进制转换为字符串

字符串为十六进制和十六进制转换为字符串

问题描述:

我能我的字符串转换为十六进制值,但不能做相反的方法:当你有个字节的字符串表示的格式“00-00字符串为十六进制和十六进制转换为字符串

Public Function StringToHex(_str$) 
    Return BitConverter.ToString(Convert.FromBase64String(_str$)) 
End Function 

Public Function HexToString(_str$) 
    'could not do this 
End Function 

Private Sub Button55_Click(sender As Object, e As EventArgs) Handles 
Button55.Click 
    lblStatus.Text = StringToHex("mankat236598") 
    'result : 99-A9-E4-6A-DD-B7-EB-9F-7C 

    lblInfo.Text = HexToString(lblStatus.Text) 
    'i want result : mankat236598 
End Sub 
+1

'“mankat236598”'不是一个Base64字符串,所以这是一个问题。您还应该启用Option Strict – Plutonix

+1

@Putonix它*是一个有效的Base64字符串。 “OpHasNotUsedOptionStrictOn”也是一个有效的Base64字符串。 –

-00“,则需要将”00“等转换为字节。你可以跳过破折号,而这样做:

Option Infer On 
Option Strict On 

Module Module1 

    Function StringToHex(s As String) As String 
     Return BitConverter.ToString(Convert.FromBase64String(s)) 
    End Function 

    ''' <summary> 
    ''' Convert hex string to bytes and then Base64 encode those bytes. 
    ''' </summary> 
    ''' <param name="hexString">Hex as a string with dashes between bytes, e.g. A0-10-FF.</param> 
    ''' <returns></returns> 
    Function HexToString(hexString As String) As String 
     Dim nBytes = (hexString.Length + 1) \ 3 
     Dim bb(nBytes - 1) As Byte 

     For i = 0 To nBytes - 1 
      Dim b = hexString.Substring(i * 3, 2) 
      bb(i) = Convert.ToByte(b, 16) 
     Next 

     Return Convert.ToBase64String(bb, Base64FormattingOptions.None) 

    End Function 

    Sub Main() 
     Dim testString = "mankat236598" 
     Dim x = StringToHex(testString) 
     Console.WriteLine(x) 

     Dim y = HexToString(x) 

     ' Check if the result is correct: 
     If y <> testString Then Console.WriteLine("Round-trip failure.") 

     Console.WriteLine(y) 

     Console.ReadLine() 

    End Sub 

End Module 
+0

感谢工作好的先生,但我不能投票需要15名声谢谢你的帮助 – DVELPR

+0

@ pc8181不客气:) –

+0

我的投票接受谢谢 – DVELPR