2017-05-28 371 views
0

我能我的字符串轉換爲十六進制值,但不能做相反的方法:當你有個字節的字符串表示的格式「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字符串。 –

回答

1

-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

相關問題