Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a byte[] of unknown size in C#?

Tags:

c#

I'm trying to create a byte[] given some unknown amount of bytes. Here's an example:

ArrayList al = new ArrayList();
al.Add(0xCA);
al.Add(0x04);
byte[] test = (byte[])al.ToArray(typeof(byte));

I'm receiving an error that one or more of the values in the array cannot be converted to a byte. What am I doing wrong here?

Thanks

like image 241
FoppyOmega Avatar asked Dec 01 '22 10:12

FoppyOmega


2 Answers

Try List<byte> and then use ToArray

like image 98
Steve Mitcham Avatar answered Dec 13 '22 02:12

Steve Mitcham


Either use a generic collection instead of a nongeneric ArrayList, or make sure you are actually using bytes. 0xCA is an int, not a byte.

        ArrayList al = new ArrayList();
        al.Add((byte)0xCA);
        al.Add((byte)0x04);
        byte[] test = (byte[])al.ToArray(typeof(byte));
like image 32
Brian Avatar answered Dec 13 '22 03:12

Brian