Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 129099
  • Last Modified:

Byte Array to String in VB

I read in an array of bytes off the network. I need to be able to split it into an array of strings. This works fine when using system.text.encoding.ASCII, except that some of the characters are greater then 127 (they're data bytes, not string bytes) but ASCII strips them off since it is only 7-bit. Is there an "ASCII 8-bit" enconding scheme or similiar? Thanks.
0
jasoncout
Asked:
jasoncout
  • 5
  • 3
  • 2
  • +8
1 Solution
 
Bob LearnedCommented:
Encoding.ASCII.GetString(myByteArray)

Bob
0
 
jasoncoutAuthor Commented:
As stated in my original question, Encoding.ASCII does not work because it is based on a 7-bit character set, and some of the characters I am reading in are 8-bit.
0
 
Bob LearnedCommented:
My bad--not paying attention.

Encoding.UTF8.GetString(myByteArray))

Bob
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jasoncoutAuthor Commented:
Are characters 0-127 the same between UTF-8 and ASCII?
0
 
jasoncoutAuthor Commented:
If a character is greater then 127 in UTF-8, doesn't it become a two-byte character? I want 0xFF to be read in as 1 character, with a value of 255.
0
 
Bob LearnedCommented:
I love those questions that push me outside of my comfort zone.  

I tried this test:

    Dim b() As Byte = {255, 128, 234, 244}

    Dim s As String = System.Text.Encoding.Default.GetString(b)

    Debug.WriteLine(s)
    Debug.WriteLine(System.Text.Encoding.Default.GetByteCount(s))

Result:

String = ÿ€êô
Byte count = 4

Default = The system's current ANSI code page.


Bob
0
 
Bob LearnedCommented:
Did this help?

Bob
0
 
misslinda454Commented:
I don't know if this will do exactly what you are looking for but it works well to convert byte arrays to strings for me. :)

 Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
        Dim i As Integer
        Dim sOutput As New StringBuilder(arrInput.Length)
        For i = 0 To arrInput.Length - 1
            sOutput.Append(arrInput(i).ToString("X2"))
        Next
        Return sOutput.ToString()
End Function
0
 
EyalLCommented:
Bob,

Try to change the first byte in your example to zero. It won't work.

The GetString function stops on zero values.

Eyal.
0
 
Bob LearnedCommented:
Strings cannot have null characters in them in VB.NET.  You would have to keep the byte array.

Bob
0
 
jazduckCommented:
Id argue that a string can have a null character in VB.NET, this seems odd however as I typically use the standard method to convert a bytearray to string. are you sure this isnt an unintended consequence of using the .Default.GetString ??

When using a line like "output = Encoding.ASCII.GetString(bytestream)" to convert bytestreams that are sent using tcp sockets, i continually have to parse the string once its converted, to cut out Chr(0)'s. Try it sometime.

Jaz
0
 
msaliCommented:
Following has worked for me well.... Old way but what can I say as I am coming from a vb6 developemnt environmnet.

for i=0 to byte_arr.length
  outStr= outStr & chr(byte_arr(i))
next

msali.
0
 
anugrahCommented:
seems as if i have reached between big boys regarding string to byte conversion,

well i just disturbed you to thank you that unknowingly your comments have helped me a lot and specially the comments from 'TheLearnedOne' was most helpful.

thanks to 'msali' also as he showed how to convert it char by char .

also i would like to contribute a small correction in msali's code ,coz his/her current code is giving array index out of bound exception.

actually u just have to replace the byte_arr.length with (byte_arr.length-1) since the length is mesured from index 1 and array starts at index of 0.
--------------------------------------------------
for i=0 to (byte_arr.length-1)
  outStr= outStr & chr(byte_arr(i))
next
--------------------------------------------------

regards to all of you
thanks again


0
 
SpoolerCommented:
I had a similar problem. When extracting a BLOB type (nText field) from MSSQL 7, i realized that the data in it had been encoded with what seems to be multi-byte charset (Unicode). But the problem was that the resulting byte array was also a multi-byte charset. Trying to use the binaryWriter with an appropriate encoding type (Default for ANSI CodePage), it took each byte of the stream as a char.

Took me a day to find how to fix it, but here it is :

'Read  data chunk from the DataReader (datRead)  and put it into outByte ( array of bytes )
retVal = datRead.GetBytes(0, startIndex, outByte, 0, bufferSize)

'Reencodes my outByte byte array to bytEncodeDef treating the source (outByte) as
'Unicode (Encoding.Unicode) and the destination as ANSI default code page (Encoding.Default)
bytEncodeDef = Encoding.Convert(Encoding.Unicode, Encoding.Default, outByte)

It should be noted that this code Imports System.Text.
0
 
super786Commented:
I wrote this program to test encodings.  Pasted below is the code for the only module in a console application.  Note that ascii certainly fails the tests.  Default and 1252 (I think the same thing) pass string to byte and vice-versa, but fail converting string to char array.  Iso-8859-1 fails the string to byte, but is interesting in that it fails the byte to string but passes the byte to string to char array test.  It also passes the string to byte to string to char array, but fails the string to char array.  I believe that part of this may be in the use of ASC vs ASCW in checking the values of the string characters.  I tested one of the failures on iso-8859-1.  The asc value of byte 128 in the converted string reads as 63 with ASC, but reads properly as 128 with ASCW.  I wrote the same tests (I think) last night in c# and iso-8859-1 passed all of them, but I have still had issues with it when reading binary data aquired from legacy VB6 and windows API systems.

I think if string to byte and byte to string work, then you shouldn't need the Char array results for passing binary data.  On the other hand, you could instead use string to char array and char array to string (A test I forgot to include) instead of string to byte and byte to string if it gives more consistent results.

Anyway, here is the module....

imports System.Text

Module Module1
   Sub Main()
            Console.WriteLine("Ascii")
            TestEncoding(Encoding.ASCII)
            Console.WriteLine("Default")
            TestEncoding(Encoding.Default)
            Console.WriteLine("1252")
            TestEncoding(1252)
            Console.WriteLine("iso-8859-1")
            TestEncoding("iso-8859-1")
            Console.WriteLine("")
            Console.WriteLine("")
            Console.WriteLine("Press enter to continue...")
            Console.ReadLine()
   End Sub
      private function TestEncoding(ByVal sName as String) as boolean
            return TestEncoding(Encoding.GetEncoding(sName))
   end function
   private function TestEncoding(ByVal iCodePage as Integer) as boolean
            return TestEncoding(Encoding.GetEncoding(iCodePage))
   end function
   private function TestEncoding(ByVal oEncoding as Encoding) as Boolean
            Dim sData as String
            dim bytData as Byte()
            Dim sMsg as string
            Dim bRet as boolean
            Dim bCheck1 as Boolean
            Dim bCheck2 as boolean
            bRet = true
            
            ReDim bytData(255)            
            Dim iCount as Integer
            for iCount = 0 to 255
                  sData += chr(iCount)
                  bytData(iCount) = CByte(iCount)
                  if bytData(iCount) <> iCount then
                        stop
                  end if
                  if Asc(sdata.Substring(iCount,1))<>iCount then
                        stop
                  end if
            next
            sMsg += "   String to byte conversion length"
            Dim bytTest as Byte() = oEncoding.GetBytes(sData)
            if bytTest.Length <> 256 then
                  sMsg = sMsg + " failed" + vbCrlf
                  bRet = false
            else
                  smsg = sMsg + " passed" + vbCrlf
            end if
            sMsg += "   Byte to string conversion length"
            dim sTest as String = oEncoding.GetString(bytData)
            if sTest.Length <> 256 then
                  sMsg = sMsg + " failed" + vbCrlf
                  bret = False
            else
                  smsg = sMsg + " passed" + vbCrlf
            end if
            bCheck1 = False
            bCheck2 = false
            for iCount = 0 to 255
                  if bCheck1 = False andalso bytTest(iCount) <> iCount then
                        sMsg += "   String to byte conversion"
                        sMsg = sMsg + " failed" + vbCrlf
                        bRet = false
                        bCheck1 = true
                        if bCheck2 then exit for
                  end if
                  if bCheck2 = False AndAlso Asc(sTest.Substring(iCount,1)) <> iCount then
                        sMsg += "   Byte to string conversion"
                        sMsg = sMsg + " failed" + vbCrlf
                        bRet = false
                        bCheck2 = true
                        if bCheck1 then exit for
                  end if
            next
            if bCheck1 = False then
                  sMsg += "   String to byte conversion passed" + vbCrlf
            end if
            if bCheck2 = False then
                  sMsg += "   Byte to string conversion passed" + vbcrlf
            end if

            Dim bytTest2 as Byte() = oEncoding.GetBytes(sTest)
            sMsg += "   Byte to string to byte conversion length"
            if bytTest2.Length <> 256 then
                  sMsg = sMsg + " failed" + vbCrlf
                  bRet = false
            else
                  smsg = sMsg + " passed" + vbCrlf
            end if
            sMsg += "   String to byte to string conversion length"
            Dim sTest2 as String = oEncoding.GetString(bytTest)
            if sTest2.Length <> 256 then
                  bRet = false
                  sMsg = sMsg + " failed" + vbCrlf
            else
                  smsg = sMsg + " passed" + vbCrlf
            end if
            bCheck1 = False
            bCheck2 = false
            for iCount = 0 to 255
                  if bCheck1 = False andalso bytTest2(iCount) <> iCount then
                        sMsg += "   Byte to string to byte conversion"
                        bRet = false
                        sMsg = sMsg + " failed" + vbCrlf
                        bCheck1 = true
                        if bCheck2 then exit for
                  end if
                  if bCheck2 = False AndAlso Asc(sTest2.Substring(iCount,1)) <> iCount then
                        sMsg += "   String to byte to string conversion"
                        bRet = false
                        sMsg = sMsg + " failed" + vbCrlf
                        bCheck2 = True
                        if bcheck1 then exit for
                  end if
            next
            if bCheck1 = False then
                  sMsg += "   Byte to string to byte conversion passed" + vbCrlf
            end if
            if bCheck2 = False then
                  sMsg += "   String to byte to string conversion passed" + vbcrlf
            end if
            sMsg += "   String to char array conversion length"
            Dim cTest as Char() = sData.ToCharArray()
            if cTest.Length <> 256 then
                  bRet = false
                  sMsg = sMsg + " failed" + vbCrlf
            else
                  sMsg += " passed" + vbCrlf
            end if
            sMsg += "   String to char array conversion"
            for iCount = 0 to 255
                  if AscW(cTest(iCount)) <> iCount then
                        bRet = false
                        sMsg = sMsg + " failed" + vbCrlf
                        exit for
                  end if
            next
            sMsg += "   Byte to String to char array conversion length"
            Dim cTest2 as Char() = sTest.ToCharArray()
            if cTest2.Length <> 256 then
                  bRet = false
                  sMsg = sMsg + " failed" + vbCrlf
            else
                  sMsg += " passed" + vbCrlf
            end if
            sMsg += "   Byte to String to char array conversion"
            for iCount = 0 to 255
                  if AscW(cTest2(iCount)) <> iCount then
                        bRet = false
                        sMsg = sMsg + " failed" + vbCrlf
                        exit for
                  end if
            next
            if iCount = 256 then sMsg += " passed" + vbCrlf

            sMsg += "   String to Byte to String to char array conversion length"
            Dim cTest3 as Char() = sTest2.ToCharArray()
            if cTest3.Length <> 256 then
                  bRet = false
                  sMsg = sMsg + " failed" + vbCrlf
            else
                  sMsg += " passed" + vbCrlf
            end if
            sMsg += "   String to Byte to String to char array conversion"
            for iCount = 0 to 255
                  if AscW(cTest2(iCount)) <> iCount then
                        bRet = false
                        sMsg = sMsg + " failed" + vbCrlf
                        Exit for
                  end if
            next
            if iCount = 256 then
                  sMsg += " passed" + vbCrlf
            end if
            
            Finished:
            
            Console.WriteLine(sMsg)
   end function
End Module
0
 
fiscCommented:
Here's what I finally came up with that worked....

Private Function ByteArrayToString(ByVal ByteArray As System.Array) As String
        'Dim s As String = System.Text.Encoding.Default.GetString(ByteArray)
        Dim strOut As String = ""
        For i As Integer = 0 To ByteArray.Length - 1
            If Not CType(ByteArray(i), Byte).ToString = 0 Then
                strOut &= System.Text.Encoding.Default.GetString(ByteArray, i, 1)
            End If
        Next
        Return strOut
    End Function
0
 
fiscCommented:
Actually, this works much more quickly....

   Private Function ByteArrayToString(ByVal ByteArray As Byte()) As String
        Return System.Text.Encoding.Unicode.GetString(ByteArray)
    End Function
0
 
akitasovCommented:
Bob's code much faster
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 3
  • 2
  • +8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now