How to convert a string to a "Null Terminated Byte Array" in C#?

Viewed 705

Suppose my string is "John Doe"

How can i convert this to a byte array?

Currently i just have the code to convert the string into a byte array, but how to make i into a null terminated byte array?

byte[] bytes = Encoding.ASCII.GetBytes("John Doe");

Thanks ahead

2 Answers

Without delving into the details of why you might need this. I assume it's for a serial port, socket or file etc.

You could use:

byte[] bytes = Encoding.ASCII.GetBytes("John Doe\0");

Demo here

If you are really bored, you could create a string or byte array extension method:

public static string ToNullTerminatedString(this string source) 
    => source + '\0';   

public static byte[] ToNullTerminatedArray(this byte[] source)
{
    byte[] newArray = new byte[source.Length + 1];
    source.CopyTo(newArray, 0);
    return newArray;
}

Initialize array with string length + 1

Set last byte in bytes array to null character should to the trick

Related