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
  • Just can simply append .TrimEnd('\0') Commented May 13, 2015 at 16:21
  • Yes, I already said this. And it doesn't work for \0 within the string. Commented May 18, 2015 at 13:17
  • See here stackoverflow.com/questions/2581325/… Commented Mar 4, 2018 at 17:30

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());
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, sure. The question was: is there an encoder that is already doing this? Since it is already processing the byte array.
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 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?
I need from A\0BC get this A How to get it?
@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.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.