Bytes and strings

  • Thread starter Thread starter John Dann
  • Start date Start date
J

John Dann

Just a detail about correctness/elegance (I think!) but it would be
useful to know for future reference:

I need to read a pre-existing binary file that contains as one of its
elements a 16-byte non-unicode string, which I need to assemble into a
..Net string for further processing. It seems like my only option for
reading the bytes from the file is to read them into a byte array. OK
well I can do this with a Binary Reader:

MyByteArray = BR.readbytes(16)

But is there then a more concise way of assembling the string?
Currently I'm doing:

For i as integer = 0 to 15
MyString &= chr(MyByteArray(i))
Next i

But is there a better way? Or are any alternatives not one-liners
either?

TIA
John Dann
 
John,
But is there a better way? Or are any alternatives not one-liners
either?
Yes there is a significantly better way.

Use a System.Text.Encoding object.

For example:

MyString = System.Text.Encoding.Default.GetString(MyByteArray)

Which will convert the byte array into a string based on the current Windows
Code Page as defined in the Regional settings in Control Panel.

Hope this helps
Jay
 
Bob,
Did you try BitConvert.ToString?

It converts the bytes to numbers then concatenates these together...

for example:

Dim bytes() As Byte = {&H42, &H6F, &H62}

Debug.WriteLine(BitConverter.ToString(bytes), "bitconverter")
Debug.WriteLine(System.Text.Encoding.Default.GetString(bytes),
"encoding")

Hope this helps
Jay
 

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

Back
Top