• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1317
  • Last Modified:

byte[] 50 characters to null terminated string

Hi,

C# .NET 2.0

I have a 50 character byte array, containing a null terminated set of chars. To convert it to a string, I decode it using standard UTF8Encoders ...

System.Text.UTF8Encoding decode = new System.Text.UTF8Encoding();
decode.GetString(myChars);

However because it is a 50 byte array I get back
SomeText\0\0\0\0\0\0\0\0\0\0\0\0\0 ... \0
The \0 being the NULL character. It does not return a string of length 8

Is there a simple way just to get the null terminated string out of the byte array without all the extra padding? I would have assumed the GetString would have does that, but when looking at the text output in binary mode, there is all the extra padding..

Cheers,
Derek
0
java_programmer
Asked:
java_programmer
  • 2
1 Solution
 
e1vCommented:
Can't you just remove it?

string s= decode.GetString(myChars);
s = s.Remove(s.IndexOf('\0'));
0
 
java_programmerAuthor Commented:
If there are only 3 characters, there are 47 null characters.

D
0
 
e1vCommented:
s.Remove(s.IndexOf('\0')) will remove every null character to the right of the first null character, so that should work
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now