views:

376

answers:

6

somehow couldn't find this with a google search, but I feel like it has to be simple...I need to convert a string to a fixed-length byte array, e.g. write "asdf" to a byte[20] array. the data is being sent over the network to a c++ app that expects a fixed-length field, and it works fine if I use a BinaryWriter and write the characters one by one, and pad it by writing '\0' an appropriate number of times.

is there a more appropriate way to do this?

+1  A: 

You can use Encoding.GetBytes.

byte[] byteArray = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(myString), byteArray, System.Math.Min(20, myString.Length);
Reed Copsey
+4  A: 
static byte[] StringToByteArray(string str, int length) 
{
    return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
}   
RedFilter
This will pad the buffer with spaces (0x20), not the null character (0x0) mentioned by the poster. Otherwise this is great.
Dathan
yes, but it works fine if I just use '\0' instead. thanks!
toasteroven
Also - make sure that "str" is not >20 characters, or you'll be in trouble...
Reed Copsey
+3  A: 

How about

String str = "hi";
Byte[] bytes = new Byte[20];
int len = str.Length > 20 ? 20 : str.Length;
Encoding.UTF8.GetBytes(str.Substring(0, len)).CopyTo(bytes, 0);
Dathan
If str.Length > 20, this will not work...
Reed Copsey
@Reed Good call. I've fixed that bug.
Dathan
+1  A: 

With unsafe code perhaps?

unsafe static void Main() {
    string s = "asdf";
    byte[] buffer = new byte[20];
    fixed(char* c = s)
    fixed(byte* b = buffer) {
        Encoding.Unicode.GetBytes(c, s.Length, b, buffer.Length);
    }
}

(the bytes in the buffer will default to 0, but you can always zero them manually)

Marc Gravell
+1  A: 
Byte[] bytes = new Byte[20];
String str = "blah";

System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
bytes = encoding.GetBytes(str);
David
+1  A: 

This is one way to do it:

  string foo = "bar";

  byte[] bytes = ASCIIEncoding.ASCII.GetBytes(foo);

  Array.Resize(ref bytes, 20);
Frank Hale