tags:

views:

73

answers:

7

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

A: 

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.

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

Also you can use UnicodeEncoding, UTF32Encoding, UTF7Encoding or UTF8Encoding

abatishchev
+3  A: 

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
LukeH
A: 

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.

Keith
+1  A: 

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

string s = Encoding.Unicode.GetString(data);
Marc Gravell
+1  A: 

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));
Andy Hopper
A: 

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

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

David