stringvb.netcharacter-encodingnull-character

Remove null Char from String after convert Byte() to String in VB.net


I have a string which comes from a dll. Supposedly, the string is converted from Byte() in the dll.

Below is snippet for how I get value from dll :

    'DLL declare : Public Function getData(boolData as Boolean, strData1 as String, strData2 as String) as Boolean 

    Call objValue.getValue(True, strValueA, strValueB) 

    strResultA = strValueA

I want to convert the string into hex value. When I tried to confirm the hex result is correct using hex converter in the internet. The hex value is not same.

I suspect it has some null value in the string because when I output the string into a textbox and convert it, it give the correct hex value. Eg: toHex(tbResultA.text), will give a correct hex value.

How to remove null character from a string? I have tried multiple ways to remove it, but it doesn't work. Here is snippet I have tried:

    1. strResultA = strValueA.Replace(vbNullChar, "")

    2. strResultA = strValueA.Replace(Chr(0, "")

    3. strResultA = strValueA.Replace(Convert.ToChar(0), "")

    4. strResultA = strValueA.Replace(Convert.vbNullChar, "")

    5. strResultA = Replace(strValueA, Chr(0), "")

Here is my snippet to convert string to hex :

    Private Function toHex(ByVal strValue As String) As String
      Dim byteArray() As Byte
      Dim hex As System.Text.StringBuilder = New System.Text.StringBuilder
      byteArray = System.Text.ASCIIEncoding.ASCII.GetBytes(strValue)
      For i As Integer = 0 To byteArray.Length - 1
         hex.Append(byteArray(i).ToString("x"))
      Next
      Return hex.ToString()
    End Function


    'My fuction calling, strHexA will be kept in a text file:
    Dim strHexA as String = toHex(strResultA)

Thanks.


Solution

  • I am not sure if there was a null. But I am sure that it is encoded as ASCII. The string suppose to be like this "!N029dR_:OV7LHdN" before hex.

    Anyway, thanks. I got the answer already. Since I know that the string will alway be 16 character.

    I use **

    strResultA = strValueA.Substring(0, 16)

    ** to get only the 16 character that I want.