David Rinck
David Rinck

Reputation: 6966

Converting String to List of Bytes

This has to be incredibly simple, but I must not be looking in the right place.

I'm receiving this string via a FTDI usb connection:

'UUU'

I would like to receive this as a byte array of

[85,85,85]

In Python, this I would convert a string to a byte array like this: [ord(c) for c in 'UUU']

I've looked around, but haven't figured this out. How do I do this in Visual Basic?

Upvotes: 4

Views: 8725

Answers (2)

Oded
Oded

Reputation: 498904

Use the Encoding class with the correct encoding.

C#:

// Assuming string is UTF8
Encoding utf8 = Encoding.UTF8Encoding();
byte[] bytes = utf8.GetBytes("UUU");

VB.NET:

Dim utf8 As Encoding = Encoding.UTF8Encoding()
Dim bytes As Byte() = utf8.GetBytes("UUU")

Upvotes: 9

Mertis
Mertis

Reputation: 288

depends on what kind of encoding you want to use but for UTF8 this works, you could chane it to UTF16 if needed.

Dim strText As String = "UUU"
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(strText)

Upvotes: 8

Related Questions