koumides
koumides

Reputation: 2504

C# Convert Byte Array with nulls to string

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

Upvotes: 2

Views: 2647

Answers (7)

David
David

Reputation: 333

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

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

Upvotes: 0

Andy Hopper
Andy Hopper

Reputation: 3678

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

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

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

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

Upvotes: 3

Keith
Keith

Reputation: 155692

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.

Upvotes: 0

LukeH
LukeH

Reputation: 269368

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

Upvotes: 6

abatishchev
abatishchev

Reputation: 100268

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

Also you can use UnicodeEncoding, UTF32Encoding, UTF7Encoding or UTF8Encoding

Upvotes: 0

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 0

Related Questions