开发者

Write string to fixed-length byte array in C#

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.

is there a more appropriate way to do this?


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


This is one way to do it:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);


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


You can use Encoding.GetBytes.

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


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)


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

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


And just for completeness, 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.


FieldOffset, maybe?

[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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜