3

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
  • A null-terminated byte string (NTBS) is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character). So just add a byte with the zero value at the end Commented Jun 25, 2020 at 5:50
  • A word of warning: Null-terminated byte arrays are usually required for interoperating with C or WINAPI code. Converting a string to a null-terminated byte array is done automatically by the interop layer, so, unless you have very special requirements, it is usually not necessary to do that yourself. If you found this question via Google, please consider that you might have an XY problem. Commented Jun 25, 2020 at 6:20

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This will be the easiest way. If the string is anything, then append the \0 at the end
easy, but pretty inefficient - I guess it all depends on throughput rates - there are much better ways of doing this if throughput matters, but then again: often it really doesn't
@MarcGravell funnily enough when I wrote this, I actually thought about mentioning allocations and Marc Gravell come to mind l say :P
@TheGeneral it is my mission in life to be that nagging voice inside your mind ("the general 'your'", not "TheGeneral your" - eek!) muttering something about allocations peridically
0

Initialize array with string length + 1

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

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.