简体   繁体   中英

convert byte[] to string

How do you convert a byte array to a string? I need to get the raw content, eg "96=A8=FC-=A8=FE", but when I use say Encoding.UTF8.GetString(bytes), it returns "96 - ". Thanks!

I think you misunderstand the content of strings. The closest you'll get to "raw content" is to use Encoding.Unicode - .NET uses UTF-16 internally, so converting to UTF-16 is effectively just a case of copying the contents of memory from the string to the byte array.

Now, to come back to your problem, what data do you have, what is it meant to represent and why ? Textual data is characters. Binary data is numbers, basically. You have to have a mapping between the two, and that's the encoding.

I have an article on Unicode which may help you, but I strongly suspect you'll need to take a step back before you make any progress.

If you're trying to convert a byte array into a string representation of those bytes as hex, you can just use BitConverter.ToString(byte[]) but I wouldn't describe that as a "raw" conversion.

EDIT: Okay, now that we have the context, it's much easier to answer. What you're looking at is quoted printable encoding. The email should specify the encoding of the quoted printable, so when you decode the QP encoding, that's what you should use. If you're not currently storing the content encoding of the original email, you should start doing so right now...

You effectively want a formatted string of the hexadecimal representation of each bytes. The question How do you convert Byte Array to Hexadecimal String, and vice versa, in C#? will show you how to get the string, and you can alter that code to add any "in-between-bytes" formatting you want.

您可能希望使用ASCII编码,而不是UTF8。

You can also use the Convert.ToBase64CharArray Method

http://msdn.microsoft.com/en-us/library/system.convert.tobase64chararray(VS.80).aspx

Convert.ToBase64CharArray (Byte[], Int32, Int32, Char[], Int32)

Converts a subset of an 8-bit unsigned integer array to an equivalent subset of a Unicode character array encoded with base 64 digits. Parameters specify the subsets as offsets in the input and output arrays, and the number of elements in the input array to convert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM