在C#中将字符串写入固定长度的字节数组

toa*_*ven 13 c# string bytearray

不知何故用谷歌搜索找不到这个,但我觉得它必须简单......我需要将字符串转换为固定长度的字节数组,例如将"asdf"写入byte[20]数组.数据通过网络发送到需要固定长度字段的c ++应用程序,如果我使用BinaryWriter并逐个写入字符,它可以正常工作,并通过写'\ 0'适当的次数填充它.

有没有更合适的方法来做到这一点?

Red*_*ter 21

static byte[] StringToByteArray(string str, int length) 
{
    return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
}   
Run Code Online (Sandbox Code Playgroud)

  • 这将填充缓冲区空格(0x20),而不是海报提到的空字符(0x0).否则这很棒. (2认同)
  • 另外 - 确保"str"不是> 20个字符,否则你将遇到麻烦...... (2认同)

Fra*_*ale 7

这是一种方法:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);
Run Code Online (Sandbox Code Playgroud)


Dat*_*han 6

怎么样

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);
Run Code Online (Sandbox Code Playgroud)