问题
hi i have this kind of array
int[] arrayint = new int[32];
and it contains
arrayint[0] = 99
arrayint[1] = 121
arrayint[2] = 99
arrayint[3] = 66
...
is there a simple way to copy that integer array into a byte array like i want to make this byte array
byte[] streambit;
and it should be the same to the arrayint value
i want to be like this the output
streambit[0] = 99
streambit[1] = 121
streambit[2] = 99
streambit[3] = 66
...
回答1:
streambit = arrayint.Select(i => (byte)i).ToArray();
Just make sure that you have no value greater than 255.
回答2:
Without LINQ (useful when targeting .Net 2.0 for instance):
byte[] bytearray = Array.ConvertAll<int, byte>(arrayint, (z) => (byte)z);
Well yeah, much more faster than LINQ:
Test code (could be improved, but this gives an idea):
private static void Main(string[] args)
{
int[] arrayint = new int[40000];
arrayint[0] = 99;
arrayint[1] = 157;
arrayint[2] = 1;
arrayint[3] = 45;
byte[] bytearray;
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
bytearray = Array.ConvertAll<int, byte>(arrayint, (z) => (byte)z);
}
sw.Stop();
Console.WriteLine("ConvertAll took {0} ms", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
bytearray = arrayint.Select(z => (byte)z).ToArray();
}
sw.Stop();
Console.WriteLine("LINQ took {0} ms", sw.ElapsedMilliseconds);
Console.ReadLine();
}
Result:
ConvertAll took 1865 ms
LINQ took 6073 ms
回答3:
streambit=arrayint.Where(x=>x>=0&&x<=255).Select(y=>(byte)y).ToArray();
来源:https://stackoverflow.com/questions/12195729/how-to-copy-int-array-value-into-byte-array-only-copy-the-value-in-c-sharp