What is the character that represents the null byte after ASCIIEncoding.GetString (byte [])?

I have a byte array that may or may not have null bytes at the end of it. After converting it to a string, I have a bunch of empty space at the end. I tried using Trim () to get rid of it, but it does not work. How can I remove all white space at the end of a line after converting an array of bytes?

I am writing this C #.

+4
source share
2 answers
public string TrimNulls(byte[] data) { int rOffset = data.Length - 1; for(int i = data.Length - 1; i >= 0; i--) { rOffset = i; if(data[i] != (byte)0) break; } return System.Text.Encoding.ASCII.GetString(data, 0, rOffset + 1); } 

In the interest of full disclosure , I would like to clearly indicate that this will only work reliably for ASCII. For any multibyte encoding, this will pop the bed.

+2
source

Trim () does not work in your case, since it only removes spaces, tabs and newlines AFAIK. It does not remove the character '\ 0'. You can also use something like this:

byte [] bts = ...;

string result = Encoding.ASCII.GetString (bts) .TrimEnd ('\ 0');

+6
source

Source: https://habr.com/ru/post/1304188/


All Articles