我想将字符串转换为 ascii 并将其存储到字节数组中。我知道最简单的方法是
编码.ASCII.GestBytes
但我想要的是
byte[] temp = new byte[];
temp = Encoding.ASCII.GestBytes("DEMO1");
因此,当我这样做时
Console.WriteLine(temp[i])
它应该打印出 68 69 77 48 0 0 0 0 0 0 0 0 0 0 0 0 而不是 68 69 77 48
我怎样才能做到这一点?
请注意,如果缓冲区太小,则会抛出:
byte[] temp = new byte[10];
string str = "DEMO1";
Encoding.ASCII.GetBytes(str, 0, str.Length, temp, 0);
没有与 UTF8 兼容的简单方法来处理它(因为 UTF8 具有可变长度字符)。对于 ASCII 和其他固定长度编码,您可以:
byte[] temp = new byte[10];
string str = "DEMO1";
Encoding.ASCII.GetBytes(str, 0, Math.Min(str.Length, temp.Length), temp, 0);
或者,一般来说,您可以:
string str = "DEMO1";
byte[] temp = Encoding.ASCII.GetBytes(str);
Array.Resize(ref temp, 10);
这甚至适用于 UTF8。