Steve Marshall said:
Hi all,
This is probably a real dumb question, but I just haven't come
across the answer...
Is there a simple way to treat a byte array as a string, or to
convert it to a string? And the converse would sometimes be useful
too, i.e.
convert/treat string as byte array.
Good question, not dumb question.
Have a look at System.Text.Encoding.GetBytes and
System.Text.Encoding.GetString.
There are some predefined Encoding objects like
System.Text.Encoding.Unicode or System.Text.Encoding.Default
You must be aware of the fact that there are many code pages. For example, a
DOS code page has 1 byte per character whereas Unicode is always 2 bytes per
character. Strings are always stored as Unicode in .Net. There are even
different DOS code pages, like US or Westeuropean. So, the number of a
character (= the character code) can be different in different code pages.
For example, the Euro sign "€" has character code &H80 in code page 1252
("Westeuropean ´(Windows)") whereas it has character code &H20AC in Unicode.
When converting from a byte array to a string, you must always know which
code page has been used to encode the array. Same in the opposite direction:
You must choose the appropriate destination encoding.
Example:
Dim b(0) As Byte
Dim s As String
b(0) = 128
s = System.Text.Encoding.Default.GetString(b)
MsgBox(s)
Armin