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?
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[] .
This is one way to do it:
string foo = "bar";
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(foo);
Array.Resize(ref bytes, 20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With