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?

3

1 Answer 1

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());
6
  • 1
    Yes, sure. The question was: is there an encoder that is already doing this? Since it is already processing the byte array. May 18, 2015 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. May 18, 2015 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? May 18, 2015 at 13:31
  • I need from A\0BC get this A How to get it? Mar 4, 2018 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. Mar 5, 2018 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.