Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String from byte array doesn't get trimmed in C#?

Tags:

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 :)

like image 665
Lazlo Avatar asked Sep 09 '09 23:09

Lazlo


2 Answers

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.

like image 57
Walt W Avatar answered Sep 28 '22 06:09

Walt W


They're not really spaces:

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

...should do the trick.

-Oisin

like image 39
x0n Avatar answered Sep 28 '22 05:09

x0n