Tutorial :C# Convert Byte Array with nulls to string



Question:

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


Solution:1

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  


Solution:2

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

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


Solution:3

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


Solution:4

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.


Solution:5

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

Also you can use UnicodeEncoding, UTF32Encoding, UTF7Encoding or UTF8Encoding


Solution:6

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.


Solution:7

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

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


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