简体   繁体   中英

Convert String to ByteArray in C#

I want to convert a String to ByteArray in C# for Decrypt some data.

When I get de String from the ByteArray created, it shows question marks (?).

Example code:

        byte[] strTemp = Encoding.ASCII.GetBytes(strData);

        MessageBox.Show(strData);
        MessageBox.Show(Encoding.ASCII.GetString(strTemp));

The string is "Ê<,,l"x¡" (With the double quotation mark) and the result to convert again to string is: ???l?x?

I hope this helps you:

To Get byte array from a string

private byte[] StringToByteArray(string str)
{
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     return enc.GetBytes(str);
}

To get a string back from byte array :

private string ByteArrayToString(byte[] arr)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetString(arr);
}

For specific of that input, this BigEndianUnicode encoding seems works fine

byte[] strTemp = Encoding.BigEndianUnicode.GetBytes(strData);

MessageBox.Show(strData);
MessageBox.Show(Encoding.BigEndianUnicode.GetString(strTemp));

`

You are getting a byte array for the ASCII representation of your string, but your string is Unicode .

C# uses Unicode to encode strings, Unicode being able to represent far more symbols as ASCII.

In your example, every symbol which has no ASCII representation is replaced by '?', this is why only 'l' and 'x' appear in the output.

The proper way to do it is to use a Unicode encoding instead:

byte[] strTemp = Encoding.UTF8.GetBytes(strData);

MessageBox.Show(strData);
MessageBox.Show(Encoding.UTF8.GetString(strTemp));

Basically, any Unicode encoding can be used: UTF8, UTF32, Unicode, BigEndianUnicode ( https://en.wikipedia.org/wiki/Comparison_of_Unicode_encodings ).

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