user2264990 user2264990 - 1 year ago 141
C# Question

How to convert string to null-terminated one?

How to convert a simple string to a null-terminated one?


Example string: "Test message"

Here are the bytes:

54 65 73 74 20 6D 65 73 73 61 67 65

I need string with bytes like follows:

54 00 65 00 73 00 74 00 20 00 6D 00 65 00 73 00 73 00 61 00 67 00 65 00 00

I could use loops, but will be too ugly code. How can I make this conversion by native methods?

Answer Source

It looks like you want a null-terminated Unicode string. If the string is stored in a variable str, this should work:

var bytes = System.Text.Encoding.Unicode.GetBytes(str + "\0");

(See it run.)

Note that the resulting array will have three zero bytes at the end. This is because Unicode represents characters using two bytes. The first zero is half of the last character in the original string, and the next two are how Unicode encodes the null character '\0'. (In other words, there is one extra null character using my code than what you originally specified, but this is probably what you actually want.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download