Search code examples
stringvb.netcarriage-returnlinefeed

How can I improve my hex-based conversion


I was facing a problem where I got data (String) from a database with Linebreaks as (Hex) 0D. I displayed this data in a Textbox, which did not use the 0D as a linbreak. I found that the Textbox needs 0D-0A (LF & CR, dont know which is which) to actually show the new line. To solve this problem I came up with the following code.

Private Function convertString(txt As String) As String
    Dim data = System.Text.Encoding.Default.GetBytes(txt)
    Dim hexString As String = BitConverter.ToString(data)
    hexString = hexString.Replace("0D", "0D-0A")
    Dim arr As [String]() = hexString.Split("-"c)
    Dim array As Byte() = New Byte(arr.Length - 1) {}
    For i As Integer = 0 To arr.Length - 1
        array(i) = Convert.ToByte(arr(i), 16)
    Next
    Return System.Text.Encoding.Default.GetString(array)
End Function

Explanation/procedure:
1. Convert String to ByteArray
2. Convert ByteArray to Hex-String (Hex-Chars separated by '-' )
3. Adding the missing lf or cr by replacing the solo one
4. Convert Hex-String back to ByteArray
5. Convert ByteArray back to String

Now my question:
I am pretty sure there is a better way to do that. How can I simplify those lines of code?


Solution

  • You should be able to just Replace vbCr with vbCrLf:

    Dim txt = "This is a" & vbCr & "test"
    Encoding.UTF8.GetBytes(txt).HexDump()
    

    gives (HexDump is a custom utility method, but not relevant to the question):

    00000000   54 68 69 73 20 69 73 20  61 0D 74 65 73 74         This is a·test  
    
    Dim txt2 = txt.Replace(vbCr, vbCrLf)
    Encoding.UTF8.GetBytes(txt2).HexDump()
    

    gives:

    00000000   54 68 69 73 20 69 73 20  61 0D 0A 74 65 73 74      This is a··test 
    

    So, your whole method would be:

    Private Function convertString(txt As String) As String
        Return txt.Replace(vbCr, vbCrLf)
    End Function