Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a byte array to a string? [duplicate]

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.

like image 803
Ian Lundberg Avatar asked Mar 22 '12 18:03

Ian Lundberg


People also ask

How does Java convert byte array to string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


2 Answers

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.

like image 125
Oded Avatar answered Oct 24 '22 00:10

Oded


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.)

like image 20
Jon Skeet Avatar answered Oct 24 '22 00:10

Jon Skeet