toasteroven
toasteroven

Reputation: 2790

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?

Upvotes: 15

Views: 25664

Answers (8)

kagali-san
kagali-san

Reputation: 3082

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/

Upvotes: 0

Glenn Slayden
Glenn Slayden

Reputation: 18749

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.

Upvotes: 1

Dathan
Dathan

Reputation: 7446

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

Upvotes: 6

Frank Hale
Frank Hale

Reputation: 1896

This is one way to do it:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);

Upvotes: 13

David
David

Reputation: 7153

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

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

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062745

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)

Upvotes: 1

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171401

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

Upvotes: 21

Reed Copsey
Reed Copsey

Reputation: 564403

You can use Encoding.GetBytes.

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

Upvotes: 3

Related Questions