Byte Array to String Array

M

Mike

Folks, I know there has to better a built-in VB.NET for converting a
byte array of asciiz strings to a string array. This works, but is
there method to do this already?

// Convert buffer of fixed size asciiz strings to string array
Function B2S(_
ByVal count As Integer,_ ' number of items
ByVal size As Integer, _ ' size of asciiz
ByVal buffer() As Byte _ ' byte buffer
) As String()
Dim list(count - 1) As String
Dim n As Integer = 0
Dim i As Integer = 0
For n = 0 To count - 1
Dim s As String = ""
For i = 0 To size - 1
Dim b As Byte = buffer(n * size + i)
If b = 0 Then Continue For
s = s + Chr(b)
Next
list(n) = s
Next
Return list
End Function

Example use:

dim count as integer = 8
dim size as integer = 24
Dim data As Byte() = New Byte(count*size - 1) {}

GetMyDLLData(count, size, data)

dim alist() as string = B2S(count,size,data)

TIA

--
 
R

roidy

Hi Mike, you can get rid of the inner loop using:-

list(n) = System.Text.Encoding.ASCII.GetString(buffer, n*size, size)

Rob
 
M

Mike

Thanks Rob!

Added a trim(char()) to remove the nulls. Here's the final function:

// Convert buffer of fixed size asciiz strings to string array
// buffer length guaranteed to by count*size
Function B2S(_
ByVal count As Integer,_ ' number of items
ByVal size As Integer, _ ' size of asciiz
ByVal buffer() As Byte _ ' byte buffer
) As String()
Dim wsp() As Char = {Chr(32), Chr(0)}
Dim list(count - 1) As String
For n As Integer = 0 To count - 1
list(n) = Text.Encoding.ASCII.GetString(buffer, _
n * size, size).Trim(wsp)
Next
Return list
End Function

// overload:: buffer is guaranteed to be count*size length
// when retrieved, so only the size each asciiz.

Function B2S(_
ByVal size As Integer, _ ' size of asciiz
ByVal buffer() As Byte _ ' byte buffer
) As String()
return B2S(CInt(buffer.Length / size),size,buffer)
End Function

Thanks again.

--
 
M

Mike

Ha! Note I added the inline comments only here. // is not supported
in VB.NET - sorry, out of habit. :)
 
R

roidy

Yep I still make the mistake of trying to use c style comments in VB......
Just habit I guess.
 

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