Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write string to fixed-length byte array in C#

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?

like image 989
toasteroven Avatar asked Apr 07 '10 20:04

toasteroven


People also ask

How to convert String to byte[] Java?

How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .


1 Answers

This is one way to do it:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);
like image 192
Frank Hale Avatar answered Sep 30 '22 02:09

Frank Hale