Convert Byte Array to String?

T

Terry Olsen

Looking for info on how to convert a byte array to a string, and string to
byte array. Thanks.
 
K

Ken Tucker [MVP]

Hi,

Dim strA As String = "A"

Dim arByte() As Byte = System.Text.Encoding.Default.GetBytes(strA)

Dim strByte As String = System.Text.Encoding.Default.GetString(arByte)



Ken
 
D

Derek Harmon

Terry Olsen said:
Looking for info on how to convert a byte array to a string, and string to byte array.

Imports System
Imports System.Text

Public Function BytesToString( ByVal buf( ) As Byte) As String
Return Encoding.Unicode.GetString( buf, 0, buf.Length)
End Function

Public Function StringToBytes( ByVal str As String) As Byte( )
Dim byteCount As Integer = Encoding.Unicode.GetByteCount( str, 0, str.Length)
Dim bytes( ) As Byte = New Byte( byteCount) { }
Encoding.Unicode.GetBytes( str, 0, str.Length, bytes, 0)
Return bytes
End Function


Derek Harmon
 
H

Herfried K. Wagner [MVP]

Terry Olsen said:
Looking for info on how to convert a byte array to a string, and string to
byte array.

Byte array -> string:

'System.Text.Encoding.<encoding>.GetString'

String -> byte array:

'System.Text.Encoding.<encoding>.GetBytes'
 
J

Jay B. Harlow [MVP - Outlook]

Terry,
As the other suggested you need to use a System.Text.Encoding object.

Which Encoding object tends to be the question.

If you have a specific encoding, The System.Text.Encoding class has shared
properties for common encodings. Encoding.Default represents the ANSI
encoding used by Windows as set by Windows Control Panel, most of the time
it is the one you want to use. Encoding.ASCII represents the ASCII encoding.
Remember that ASCII is defined to be 7 bit characters (code points 0 to
127), while ANSI is 8 bit characters based on a specific code page (code
points 0 to 255).

For information on Encodings, Unicode & such see:

http://www.yoda.arachsys.com/csharp/unicode.html

Hope this helps
Jay
 
G

Guest

Everybody is right.
But I use a lot of
Convert.FromBase64String Method
Convert.ToBase64String Method

Rulin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top