How to convert byte array to string?

I have a byte, which is an array of 30 bytes, but when I use BitConverter.ToString , it displays the sixth line. The byte is 0x42007200650061006B0069006E00670041007700650073006F006D0065 . This is also in Unicode.

This means BreakingAwes.me, but I'm not sure how to make it convert from hex to Unicode to ASCII.

+7
source share
2 answers

You can use one of the Encoding classes - you need to know what the encoding of these bytes is.

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

The values ​​you specify look like Unicode encoding, so UTF8 or Unicode look like good bets.

+14
source

It looks like this is a little-endian UTF-16, so you want Encoding.Unicode :

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

Usually you should not assume what encoding is - it should be what you know about data. For other encodings, you obviously use different instances of Encoding , but Encoding is the right class for binary representations of text.

EDIT: As noted in the comments, it seems to you that “00” is missing either from the beginning of your byte array (in this case you need Encoding.BigEndianUnicode ) or from the end (in this case only Encoding.Unicode fine).

(When it comes to the opposite, accepting arbitrary binary data and presenting it as text, you should use hex or base64. This is not the case, but you should know about it.)

+4
source

All Articles