1

I have a c# string like this:

string a = "Hello";
  1. How can I use the Encoding class to get the exact length of characters including null-terminating characters? For example, if I used Encoding.Unicode.GetByteCount, I should get 12 and if I used Encoding.ASCII.GetByteCount, I should get 6.
  2. How can I use the Encoding class to encode the string into a byte array including the null-terminating characters?

Thank you for help!

2
  • Given that a null terminator is a single zero byte, the conversion is hardly challenging. Commented Sep 6, 2014 at 10:38
  • 1
    Why are you doing this? If you are trying to use a C API, you should check out the Marshal class instead. Commented Sep 6, 2014 at 10:38

2 Answers 2

1

As far as I remember, null-termination is a specific thing to C/C++'y languages/platforms. Unicode and ANSI encodings does not specify any requirement for the string to be null-terminated, nor does the C#/CLR platform. You can't expect them to include that extra character. So you will probably have a hard time making those classes emit that from yours 5-character "Hello" string.

However, in C#/CLR, strings can contain null characters.

So, basing on that, try converting the following this 6-character string:

string a = "Hello\0";

or

string a = "Hello";
a += "\0"; // if you really can't have the \0 at first time, you can simply add it

and I'm pretty sure you will get the result you wanted through both Encoding.ANSI and Encoding.Unicode (single \0 in ANSI, single \0 in UTF, \0\0 in UTF16 etc..)

(Also, note that if you are P/Invoking, then you don't need to handle that manually. The Marshaller will nullterminate the string correctly, assuming the datatype set is considered to be string-like data and not array-like data.)

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

Comments

1

In .NET, strings are not null terminated, so you need to add the null character yourself if the protocol you're working with requires one. That means:

  1. You need to manually add 1 to the string length.
  2. You need to manually write a null character (e.g. (byte)0) to the end of the byte array.

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.