2

All,

I have a question about converting byte arrays with nulls to C# string. Here is an example of my byte array that I would like to convert to string. I expect to get a string with value SHKV

[0]: 83
[1]: 0
[2]: 72
[3]: 0
[4]: 75
[5]: 0
[6]: 86
[7]: 0

How can I do it in C# ?

Thanks, MK

7 Answers 7

6

You really need to know the original encoding in order to convert it successfully.

I suspect that in this case the encoding is probably UTF-16, which you can convert as follows:

byte[] yourByteArray = new byte[] { 83, 0, 72, 0, 75, 0, 86, 0 };

string yourString = Encoding.Unicode.GetString(yourByteArray));

Console.WriteLine(yourString);    // SHKV
Sign up to request clarification or add additional context in comments.

Comments

3

That looks like little-endian UTF-16, so:

string s = Encoding.Unicode.GetString(data);

Comments

1

Are you guaranteed to always see this encoding of the strings (char, null, char, null, etc.)? If so, you can simply use the Unicode string encoder to decode it:

    Byte[] contents = new Byte[] {83, 0, 72, 0, 75, 0, 86, 0};
    Console.WriteLine(System.Text.Encoding.Unicode.GetString(contents));

Comments

0

Assuming ASCII bytes, you can do use LINQ:

new string(bytes.Where(b => b != 0).Select(b => (char)b).ToArray());

However, I suspect that you're trying to hack away Unicode data.

DON'T.

Instead, use the Encoding class.

Comments

0
string str = new ASCIIEncoding().GetString(bytes.Where(i => i != 0).ToArray());

Also you can use UnicodeEncoding, UTF32Encoding, UTF7Encoding or UTF8Encoding

Comments

0

Using Linq syntax:

var chars = 
    from b in byteArray
    where b != 0
    select (char) b;

string result = new String(chars.ToArray());

Though you are better off selecting the right encoding instead, as others have suggested.

Comments

0

byte[] b = new byte[]{83,0,72,0,75,0,86,0};

System.Text.Encoding.Unicode.GetString(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.