How to copy int array value into byte array? only copy the value in C#

[亡魂溺海] 提交于 2019-12-11 11:47:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!