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?