15

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?

8 Answers 8

21
static byte[] StringToByteArray(string str, int length) 
{
    return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
}   
Sign up to request clarification or add additional context in comments.

2 Comments

This will pad the buffer with spaces (0x20), not the null character (0x0) mentioned by the poster. Otherwise this is great.
This doesn't work if the text is longer than length. If we have 50 bytes long string, and we use this method with length parameter 30, we got 50 bytes long byte array instead of 30.
13

This is one way to do it:

  string foo = "bar";

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

  Array.Resize(ref bytes, 20);

Comments

6

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

1 Comment

@Reed Good call. I've fixed that bug.
3

You can use Encoding.GetBytes.

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

1 Comment

using System.Math.Min is a smart approach.
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)

Comments

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

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

1 Comment

Last line will overwrite your bytes with a new array length of 4.
1

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.