1

When converting a byte array to a string I'm using something like this

byte[] src = new byte[5] { 65, 66, 67, 0, 0 };
string s = System.Text.Encoding.Default.GetString(src);

(also see here: How to convert byte[] to string?)

However, if the byte array contains values of 0 at some positions (e.g. at the end, because the expected string was not long enough), the resulting string also contains '\0' characters. They even count for string.Length. The result from the above example is "ABC\0\0", length is 5.

Such a string is printable but Console.Writeline seems to have problems with linefeeds after such a string. And comparing this string to "real" strings may have unexpected results because of the "hidden" '\0' characters ("ABC" != "ABC\0\0").

Since I'm currently using this for debug output only, my workaround is to Trim() trailing '\0' characters. Is there a better way to get rid of this, maybe a different encoder or a different conversion method?

Community
  • 1
  • 1
Cpt. Obvious
  • 21
  • 1
  • 4

1 Answers1

4

Well, why don't just simply throw these \0 away from your array before conversion to string?
Strings in C# are not null-terminated, so there is no reason to keep any \0.

For example, by using Linq:

string s = System.Text.Encoding.Default.GetString(src.Where(x => x != 0).ToArray());
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • 1
    Yes, sure. The question was: is there an encoder that is already doing this? Since it is already processing the byte array. – Cpt. Obvious May 18 '15 at 13:22
  • Both default encoder and Ascii encoder (tried this) return strings that are not quite "standard" since they may contain \0, even in the middle of the string. – Cpt. Obvious May 18 '15 at 13:27
  • @Cpt.Obvious not sure if I understand you now. Are you trying to get rid of `0` bytes anywhere in your source array before encoding this array to string? If yes - I've shown you one of possible ways. Or you trying to accomplish some other task? – Andrey Korneyev May 18 '15 at 13:31
  • I need from `A\0BC` get this `A` How to get it? – Andrei Krasutski Mar 04 '18 at 16:45
  • @AndreiKrasutski this depends on your exact requirement. if you need strictly characters before first occurence of `\0` char - you can use `string.IndexOf` and `string.Substring` or something similar. – Andrey Korneyev Mar 05 '18 at 12:09
  • @AndyKorneyev I decided it with the help of `Marshal.PtrToStringAnsi` his is the best solution – Andrei Krasutski Mar 05 '18 at 19:22