Home > Enterprise >  Convert TCP/IP received ASCII to HEX and put it inside Bracket
Convert TCP/IP received ASCII to HEX and put it inside Bracket

Time:07-22

My printer send me ASCII from TCP/IP port but I need to convert those ASCII to Hex and put it inside Bracket and display on textbox 2. when i run the following code for 0705 Hex it is showing ??75 on textbox 2. my desired output is [07][05]

    If TCPClientStream.DataAvailable = True Then
        Dim rcvbytes(TCPClientz.ReceiveBufferSize) As Byte
        TCPClientStream.Read(rcvbytes, 0, CInt(TCPClientz.ReceiveBufferSize))
        TextBox3.Text = System.Text.Encoding.ASCII.GetString(rcvbytes)

        For Each c As Char In TextBox3.Text
            TextBox3.Text &= Convert.ToString(Convert.ToInt32(c), 16)
        Next

    End If

CodePudding user response:

You have a couple of errors in your code.

  • You are not checking how many bytes were actually received.
  • You are not using the correct method to convert to a hex string.
    Either use Convert.ToHexString in .NET 5 ....
Dim rcvbytes(TCPClientz.ReceiveBufferSize) As Byte
If TCPClientStream.DataAvailable = True Then
    Dim Received = TCPClientStream.Read(rcvbytes, 0, CInt(TCPClientz.ReceiveBufferSize))
    TextBox3.Text &= Convert.ToHexString(rcvbytes, 0, Received)
End If
  • ... or you can use BitConverter.ToString and Replace
Dim rcvbytes(TCPClientz.ReceiveBufferSize) As Byte
If TCPClientStream.DataAvailable = True Then
    Dim Received = TCPClientStream.Read(rcvbytes, 0, CInt(TCPClientz.ReceiveBufferSize))
    TextBox3.Text &= BitConverter.ToString(rcvbytes, 0, Received).Replace("-", "")
End If
  • Related