【发布时间】:2010-04-07 20:19:17
【问题描述】:
不知何故无法通过谷歌搜索找到它,但我觉得它必须很简单......我需要将字符串转换为固定长度的字节数组,例如将“asdf”写入byte[20] 数组。数据正在通过网络发送到需要固定长度字段的 c++ 应用程序,如果我使用 BinaryWriter 并一个一个地写入字符,然后通过写入 '\0' 来填充它,它可以正常工作次数。
有没有更合适的方法来做到这一点?
【问题讨论】:
不知何故无法通过谷歌搜索找到它,但我觉得它必须很简单......我需要将字符串转换为固定长度的字节数组,例如将“asdf”写入byte[20] 数组。数据正在通过网络发送到需要固定长度字段的 c++ 应用程序,如果我使用 BinaryWriter 并一个一个地写入字符,然后通过写入 '\0' 来填充它,它可以正常工作次数。
有没有更合适的方法来做到这一点?
【问题讨论】:
static byte[] StringToByteArray(string str, int length)
{
return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
}
【讨论】:
length,这将不起作用。如果我们有 50 字节长的字符串,并且我们将这个方法与 length 参数 30 一起使用,我们得到 50 字节长的字节数组而不是 30。
这是一种方法:
string foo = "bar";
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(foo);
Array.Resize(ref bytes, 20);
【讨论】:
怎么样
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);
【讨论】:
您可以使用Encoding.GetBytes。
byte[] byteArray = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(myString), byteArray, System.Math.Min(20, myString.Length);
【讨论】:
也许有不安全的代码?
unsafe static void Main() {
string s = "asdf";
byte[] buffer = new byte[20];
fixed(char* c = s)
fixed(byte* b = buffer) {
Encoding.Unicode.GetBytes(c, s.Length, b, buffer.Length);
}
}
(缓冲区中的字节默认为 0,但您始终可以手动将它们归零)
【讨论】:
Byte[] bytes = new Byte[20];
String str = "blah";
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
bytes = encoding.GetBytes(str);
【讨论】:
bytes。
为了完整起见,LINQ:
(str + new String(default(Char), 20)).Take(20).Select(ch => (byte)ch).ToArray();
对于变体,这个 sn-p 还选择将 Unicode 字符直接转换为 ASCII,因为前 127 个 Unicode 字符被定义为与 ASCII 匹配。
【讨论】:
FieldOffset,也许吧?
[StructLayout(LayoutKind.Explicit)]
public struct struct1
{
[FieldOffset(0)]
public byte a;
[FieldOffset(1)]
public int b;
[FieldOffset(5)]
public short c;
[FieldOffset(8)]
public byte[] buffer;
[FieldOffset(18)]
public byte d;
}
(c)http://www.developerfusion.com/article/84519/mastering-structs-in-c/
【讨论】: