Tutorial :C# Convert Byte Array with nulls to string



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


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  


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

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


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


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.


Instead, use the Encoding class.


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

Also you can use UnicodeEncoding, UTF32Encoding, UTF7Encoding or UTF8Encoding


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.


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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »