22

I have a byte array similar to this (16 bytes):

71 77 65 72 74 79 00 00 00 00 00 00 00 00 00 00

I use this to convert it to a string and trim the ending spaces:

ASCIIEncoding.ASCII.GetString(data).Trim();

I get the string fine, however it still has all the ending spaces. So I get something like "qwerty.........." (where dots are spaces due to StackOverflow).

What am I doing wrong?

I also tried to use .TrimEnd() and to use an UTF8 encoding, but it doesn't change anything.

Thanks in advance :)

2
  • 3
    Does your byte array end in 00 bytes or 20 bytes? A space is 0x20 not 0x00. Commented Sep 9, 2009 at 23:14
  • 1
    If your byte array comes from a MemoryStream, make sure that you call ToArray() and not GetBuffer(), as GetBuffer will include "unfilled" data, resulting in all those `\0's Commented Dec 15, 2014 at 15:16

5 Answers 5

33

You have to do TrimEnd(new char[] { (char)0 }); to fix this. It's not spaces - it's actually null characters that are converted weirdly. I had this issue too.

Sign up to request clarification or add additional context in comments.

4 Comments

null terminators have nothing to do with ASCII encoding. It seems @Lazlo has a fixed-sized byte array that holds a variable-lengthed ASCII encoded string, so the string has to be padded with null terminators to match the array size
Thank you :) I thought it was something like this, but didn't dare trying.
Actually, you can just do .TrimEnd('\0').
@dtb could you please elaborate a bit more? Why should the resulting string be matched with array size? Zeroes aren't ASCII characters, so logically these should be ignored, a.k.a. trimmed off, and the string should be shorter than the array.
23

They're not really spaces:

System.Text.Encoding.ASCII.GetString(byteArray).TrimEnd('\0')

...should do the trick.

-Oisin

Comments

8

Trim by default removes only whitespace, where whitespace is defined by char.IsWhitespace.

'\0' is a control character, not whitespace.

You can specify which characters to trim using the Trim(char[]) overload:

string result = Encoding.ASCII.GetString(data).Trim(new char[] { '\0' });

Comments

1

Why try to create the string first and trim it second? This could add a lot of overhead (if the byte[] is large).

You can specify index and count in the GetString(byte[] bytes, int index, int count) overload.

int count = data.Count(bt => bt != 0); // find the first null
string result = Encoding.ASCII.GetString(data, 0, count); // Get only the characters you want

Comments

0

In powershell, you can do this:

$yourString.TrimEnd(0x00)

Comments

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.