locked
Converting type "string" to type "byte()" RRS feed

  • Question

  • Hi.

     

    How do I convert a string to an 8-bit byte array?

     

    Thanks,

    Fredrik.

    Tuesday, June 12, 2007 3:26 PM

Answers

  • Call the GetBytes method for the encoding you wish to use. 

     

    For example:

     

    Code Snippet

    Dim s As String = "Hello"

    Dim bytes As Byte()

     

    bytes = Encoding.Default.GetBytes(s)  'Gets the bytes using the default encoding

     

    'or

     

    bytes = Encoding.ASCII.GetBytes(s)   'Gets the bytes using ASCII encoding

     

     

    Hope this helps

     

    Chris

    Tuesday, June 12, 2007 4:37 PM
  • Public Class Form1

     

        Private Sub Button1_Click(ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles Button1.Click

            Dim s As String = "abcdef"

            Dim b(s.Length - 1) As Byte

            For x As Integer = 1 To s.Length

                b(x - 1) = CType(Asc(Mid(s, x, 1)), Byte)

            Next

            ' write the byte array to a file to look at

            System.IO.File.WriteAllBytes("c:\look3.fil", b)

     

        End Sub

    End Class

     

    Tuesday, June 12, 2007 4:40 PM

All replies

  • Call the GetBytes method for the encoding you wish to use. 

     

    For example:

     

    Code Snippet

    Dim s As String = "Hello"

    Dim bytes As Byte()

     

    bytes = Encoding.Default.GetBytes(s)  'Gets the bytes using the default encoding

     

    'or

     

    bytes = Encoding.ASCII.GetBytes(s)   'Gets the bytes using ASCII encoding

     

     

    Hope this helps

     

    Chris

    Tuesday, June 12, 2007 4:37 PM
  • Public Class Form1

     

        Private Sub Button1_Click(ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles Button1.Click

            Dim s As String = "abcdef"

            Dim b(s.Length - 1) As Byte

            For x As Integer = 1 To s.Length

                b(x - 1) = CType(Asc(Mid(s, x, 1)), Byte)

            Next

            ' write the byte array to a file to look at

            System.IO.File.WriteAllBytes("c:\look3.fil", b)

     

        End Sub

    End Class

     

    Tuesday, June 12, 2007 4:40 PM
  • Chris found a better way.

    You may need the prefix for his code

    bytes = System.Text.Encoding.Default.GetBytes(s)

    Tuesday, June 12, 2007 4:46 PM
  • You might want characters rather than bytes if you don't know or care about the encoding:

    Code Snippet

    Dim S As String = "abcdefg"

    Dim C As Char() = CType(S, Char())

     

    Tuesday, June 12, 2007 5:55 PM
  • See my blog post I just wrote about the various ways from string to a byte array.

    1)Use ToCharArray function off of string instance.

    2)Use System.Text.Encoding.GetBytes(string)

    3)Use LINQ to automate the creation and typing of the sequence.

    Friday, June 15, 2007 3:03 PM