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)
这是一种方法:
string foo = "bar";
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(foo);
Array.Resize(ref bytes, 20);
Run Code Online (Sandbox Code Playgroud)
怎么样
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)
| 归档时间: |
|
| 查看次数: |
18236 次 |
| 最近记录: |