How do I convert a byte array to a string?

28,092

Solution 1

You can use one of the Encoding classes - you will need to know what encoding these bytes are in though.

string val = Encoding.UTF8.GetString(myByteArray);

The values you have displayed look like a Unicode encoding, so UTF8 or Unicode look like good bets.

Solution 2

It looks like that's little-endian UTF-16, so you want Encoding.Unicode:

string text = Encoding.Unicode.GetString(bytes);

You shouldn't normally assume what the encoding is though - it should be something you know about the data. For other encodings, you'd obviously use different Encoding instances, but Encoding is the right class for binary representations of text.

EDIT: As noted in comments, you appear to be missing an "00" either from the start of your byte array (in which case you need Encoding.BigEndianUnicode) or from the end (in which case just Encoding.Unicode is fine).

(When it comes to the other way round, however, taking arbitrary binary data and representing it as text, you should use hex or base64. That's not the case here, but you ought to be aware of it.)

Share:
28,092
Ian Lundberg
Author by

Ian Lundberg

Updated on September 09, 2020

Comments

  • Ian Lundberg
    Ian Lundberg over 3 years

    I have a byte that is an array of 30 bytes, but when I use BitConverter.ToString it displays the hex string. The byte is 0x42007200650061006B0069006E00670041007700650073006F006D0065. Which is in Unicode as well.

    It means B.r.e.a.k.i.n.g.A.w.e.s.o.m.e, but I am not sure how to get it to convert from hex to Unicode to ASCII.

  • Ian Lundberg
    Ian Lundberg about 12 years
    thanks you so much! haha it worked.
  • Jon Skeet
    Jon Skeet about 12 years
    @IanLundberg: Note that if you use Encoding.UTF8 you'll get a string which is twice as long as it should be for your input data. In some output forms you may not see that, but every other character will be U+0000.
  • Ian Lundberg
    Ian Lundberg about 12 years
    oh okay I didn't realize that