Dominique
Dominique

Reputation: 17565

How to show an array of bytes as a string-like list of characters?

I am using a TCP-client program to catch a list of bytes, and when I send such a list of bytes, this is what I see:

Hercules screenshot

I want to capture those characters in a logfile, so I did the following:

log.Debug($"Sending telegram=.... SocketPacket.Data=[{socketPacket.Data.ToString()}]")

The socketPacket.Data is an array of bytes, as you can see from this definition:

Public Property Data() As Byte()

But instead of seeing the desired characters, this is what I see:

Sending telegram=[.... SocketPacket.Data=[System.Byte[]]

Does anybody know how to convert an array of bytes into a string of characters in VB.Net?

Upvotes: 1

Views: 72

Answers (3)

Filburt
Filburt

Reputation: 18082

Since .ToString() doesn't do it for you, you'll have to Join your array:

log.Debug($"Sending telegram=.... SocketPacket.Data=[{String.Join(String.Empty, socketPacket.Data)}]")

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76943

The docs give you this example:

Private Function UnicodeBytesToString(
    ByVal bytes() As Byte) As String

    Return System.Text.Encoding.Unicode.GetString(bytes)
End Function

You can of course choose other encodings.

Explanation: In order to be able to convert an array of raw bytes into strings we need to understand what encoding needs to be chosen. Because the same byte array looks differently as an ASCII string than in UTF-8, for example.

Upvotes: 3

Dominique
Dominique

Reputation: 17565

In the meantime, I've discovered four ways to do this:

{BitConverter.ToString(socketPacket.Data)}
{System.Text.Encoding.ASCII.GetString(socketPacket.Data)}
{System.Text.Encoding.UTF8.GetString(socketPacket.Data)}
{String.Join(" ", socketPacket.Data.Select(Function(b) b.ToString("X2")))}

The first and the last can be used for hexadecimal representation, while the second and the third show the actual characters.

Upvotes: 2

Related Questions