简体   繁体   中英

Get a Null-Terminated String when using Encoding.ANSI or Encoding.Unicode

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!

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 (eg (byte)0 ) to the end of the byte array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM