Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert Byte Array with nulls to string

Tags:

string

c#

encode

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

like image 723
koumides Avatar asked Jan 26 '26 11:01

koumides


2 Answers

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
like image 52
LukeH Avatar answered Jan 28 '26 00:01

LukeH


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

string s = Encoding.Unicode.GetString(data);
like image 26
Marc Gravell Avatar answered Jan 27 '26 23:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!