Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a null terminated string from a C# string?

Tags:

  • I am communicating with a server who needs null terminated string
  • How can I do this smartly in C#?
like image 697
Betamoo Avatar asked May 08 '10 09:05

Betamoo


People also ask

How do you copy a null-terminated string?

strcpy() — Copy Strings The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.

Does C automatically null terminate strings?

C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose. NUL is guaranteed to have the integer value zero.

How do you string is null in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

Can you print a null character in C?

The null character is only used to signify the end of a string, and should not be printed. More than one call to printf() can contribute to the same 'formatted line'.


1 Answers

I think the smart way is to do it simply.

string str = "An example string" + char.MinValue; // Add null terminator.

Then convert it into bytes to send to the server.

byte[] buffer = ASCIIEncoding.ASCII.GetBytes(str);

Of course what encoding you use depends on what encoding the server expects.

like image 64
Alex McBride Avatar answered Oct 05 '22 02:10

Alex McBride