How do I get bytes including a null termination char from a string? [duplicate]

谁都会走 提交于 2020-12-12 18:13:10

问题


Hello StackOverflowers,

I read somewhere that C# string are not null terminated. M'fine ! But I'd like to know if the method :

byte[] myBytes = Encoding.ASCII.GetBytes(myString);

add a null termination character to the end of the array or if I must do it manually ? (the C system which will use this array does need it).

If manual, I guess the way would be :

byte[] myBytes = Encoding.ASCII.GetBytes(myString + '\0');

The data is meant to be ASCII, no worries about encoding.


回答1:



add a null termination character to the end of the array or if I must do it manually

TL;DR - it depends. You don't need it for pure .NET development. If you intend to use p-invoke to native code, well .NET does the translation for you, so again you don't.


I read somewhere that C# string are not null terminated

Correct.

MSDN:

A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). The Length property of a string represents the number of Char objects it contains, not the number of Unicode character. - Tell me more...

OP:

But I'd like to know if the method byte[] myBytes = Encoding.ASCII.GetBytes(myString); add a null termination character to the end of the array or if I must do it manually

No it doesn't and you don't need to, unless of course you wish to pass a string to native code via p-invoke but that is a completely different question (and is handled for you anyway by .NET).




回答2:


It doesn't add, your second code will work.

byte[] myBytes = 
         Encoding.ASCII.GetBytes("A"); // gives {65}

byte[] myBytes = 
    Encoding.ASCII.GetBytes("A"+"\0"); // gives {65, 0}



回答3:


GetBytes does not add a null termination character. According to this SO answer, you can just add char.MinValue to the end of your string.

byte[] myBytes = Encoding.ASCII.GetBytes(myString + char.MinValue);



回答4:


From MSDN

Your Unicode applications should always cast zero to TCHAR when using null-terminated strings.

So, to have a null-terminated string, we have to add a byte in the end by this code. The default value of byte is 0

byte[] bytes= Encoding.Default.GetBytes(myString);
byte[] bytesNull = new byte[bytes.Length + 1];
bytes.CopyTo(bytesNull , 0);


来源:https://stackoverflow.com/questions/51382103/how-do-i-get-bytes-including-a-null-termination-char-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!