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

I am trying to create byte [], given a certain number of bytes. Here is an example:

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

I get an error that one or more of the values ​​in the array cannot be converted to bytes. What am I doing wrong here?

thanks

+4
source share
3 answers

Use a common collection instead of an unstructured ArrayList or make sure that 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)); 
+9
source

Try List<byte> and then use ToArray

+11
source

Use List<byte> as shown below. When you use an ArrayList and then call al.Add (0xCA), you actually add an int to the ArrayList.

 List<byte> al = new List<byte>(); ... 
0
source

Source: https://habr.com/ru/post/1315083/


All Articles