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

12,747

Solution 1

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'd like to be very clear that this will only work reliably for ASCII. For any multi-byte encoding this will crap the bed.

Solution 2

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

byte[] bts = ...;

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

Share:
12,747
Brian
Author by

Brian

Updated on June 06, 2022

Comments

  • Brian
    Brian almost 2 years

    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 blank space at the end. I tried using Trim() to get rid of it, but it doesn't work. How can I remove all the blank space at the end of the string after converting the byte array?

    I am writing this is C#.

  • Jim Mischel
    Jim Mischel about 14 years
    Please add that your solution works great for ASCII encoding (as the OP requested), but will break horribly for anything else.
  • Brian
    Brian about 14 years
    That will work. Thanks. i was hoping to be able to do something like Trim on the resulting string, but I guess not. Thanks!
  • Brian
    Brian about 14 years
    Small bug with this solution. The return value should be: return System.Text.Encoding.ASCII.GetString(data, 0, rOffset+1); Otherwise it will cut off the last byte.
  • Adam Robinson
    Adam Robinson about 14 years
    @Brian: I already added that a few minutes ago, but thanks ;)
  • Daniel Dolz
    Daniel Dolz over 8 years
    Perhaps not the most eficcient one for me (having 20k of "0"s) but worked as a charm. Thanks