Convert Byte to String in VB.NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shadabahmad
    New Member
    • Mar 2011
    • 1

    Convert Byte to String in VB.NET

    Hi All!

    I had tried to search many forums to get this code.

    Yes, just for a single line code. But when everything else failed, I decided to write my own. And it is really working good.

    Code:
        Private Function Byte2Str(ByVal gByte() As Byte) As String
            Dim X As Integer
            Dim gTmp As String = ""
            For X = 0 To gByte.Length - 1
                gTmp = gTmp & Chr(gByte(X))
            Next
            Return gTmp
        End Function
    Br,
    Shadab Ahmad
  • yarbrough40
    Contributor
    • Jun 2009
    • 320

    #2
    this is easier:
    Code:
    Dim s as String = System.Text.ASCIIEncoding.ASCII.GetString(gByte)

    Comment

    • !NoItAll
      Contributor
      • May 2006
      • 297

      #3
      It would work faster if you used a stringbuilder instead of string - otherwise it has to recreate the entire string with each concatenation.

      Code:
      Private Function Byte2Str(ByVal gByte() As Byte) As String
      
              Dim gTmp As New System.Text.StringBuilder
              For X as Int32 = 0 To (gByte.Length - 1)
                  gTmp.append(Chr(gByte(X)))
              Next
              Return gTmp.ToString
      
      End Function
      But here is a way that appears to be even better from experts exchange - try this instead

      Code:
         Private Function ByteArrayToString(ByVal ByteArray As Byte()) As String
              Return System.Text.Encoding.Unicode.GetString(ByteArray)
          End Function

      Comment

      • !NoItAll
        Contributor
        • May 2006
        • 297

        #4
        One problem with using the system.text.enc oding method is that it will assume you want the data converted to one of the encoding methods. Raw is not one of the methods available and so you can actually wind up with something you may not expect (unless you really do want ASCII, or Unicode, or UTF8).
        AFAIK - if you want it raw then you need to use the looping method.

        Comment

        Working...