用c#将字符串写入固定长度的字节数组

时间:2022-09-29 21:37:31

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.

在谷歌搜索中找不到这个,但我觉得它必须很简单……我需要将一个字符串转换为一个固定长度的字节数组,例如,将“asdf”写入一个字节[20]数组。数据正在通过网络发送到一个c++应用程序,该应用程序需要一个固定长度的字段,如果我使用一个BinaryWriter,一个接一个地写字符,并通过写“\0”适当的次数来填充它,那么它就可以正常工作。

is there a more appropriate way to do this?

有更合适的方法吗?

8 个解决方案

#1


19  

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

#2


5  

How about

如何

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);

#3


4  

This is one way to do it:

这是一种方法:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);

#4


2  

You can use Encoding.GetBytes.

您可以使用Encoding.GetBytes。

byte[] byteArray = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(myString), byteArray, System.Math.Min(20, myString.Length);

#5


1  

With unsafe code perhaps?

也许不安全代码?

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);
    }
}

(the bytes in the buffer will default to 0, but you can always zero them manually)

(缓冲区中的字节默认为0,但是您可以手动将它们归零)

#6


1  

Byte[] bytes = new Byte[20];
String str = "blah";

System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
bytes = encoding.GetBytes(str);

#7


1  

And just for completeness, LINQ:

为了完整性,LINQ:

(str + new String(default(Char), 20)).Take(20).Select(ch => (byte)ch).ToArray();

For variation, this snippet also elects to cast the Unicode character directly to ASCII, since the first 127 Unicode characters are defined to match ASCII.

对于变体,这个代码片段还选择将Unicode字符直接转换为ASCII,因为前面的127个Unicode字符被定义为匹配ASCII。

#8


0  

FieldOffset, maybe?

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/

(c)http://www.developerfusion.com/article/84519/mastering-structs-in-c/

#1


19  

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

#2


5  

How about

如何

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);

#3


4  

This is one way to do it:

这是一种方法:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);

#4


2  

You can use Encoding.GetBytes.

您可以使用Encoding.GetBytes。

byte[] byteArray = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(myString), byteArray, System.Math.Min(20, myString.Length);

#5


1  

With unsafe code perhaps?

也许不安全代码?

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);
    }
}

(the bytes in the buffer will default to 0, but you can always zero them manually)

(缓冲区中的字节默认为0,但是您可以手动将它们归零)

#6


1  

Byte[] bytes = new Byte[20];
String str = "blah";

System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
bytes = encoding.GetBytes(str);

#7


1  

And just for completeness, LINQ:

为了完整性,LINQ:

(str + new String(default(Char), 20)).Take(20).Select(ch => (byte)ch).ToArray();

For variation, this snippet also elects to cast the Unicode character directly to ASCII, since the first 127 Unicode characters are defined to match ASCII.

对于变体,这个代码片段还选择将Unicode字符直接转换为ASCII,因为前面的127个Unicode字符被定义为匹配ASCII。

#8


0  

FieldOffset, maybe?

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/

(c)http://www.developerfusion.com/article/84519/mastering-structs-in-c/