嗚嗚喔學習筆記: 9月 2023

搜尋此網誌

2023年9月14日 星期四

C# int[] to byte[] , byte[] to int[]



public class ByteAyParser
{
    public static byte[] IntAy2ByteAy(int[] intAy)
    {
        int byteCount = intAy.Length * 4;
        byte[] byteAy = new byte[byteCount];

        for (int i = 0; i < intAy.Length; i++)
        {
            int val = intAy[i];
            byteAy[i * 4 + 3] = (byte)((val >> 24) & 0xFF);
            byteAy[i * 4 + 2] = (byte)((val >> 16) & 0xFF);
            byteAy[i * 4 + 1] = (byte)((val >> 8) & 0xFF);
            byteAy[i * 4 + 0] = (byte)(val & 0xFF);
        }

        return byteAy;
    }
    public static int[] ByteAy2IntAy(byte[] byteAy)
    {
        if (byteAy.Length % 4 != 0)
        {
            Debug.LogErrorFormat("ByteAy2IntAy byteAy.Length {0} not a multiple of 4", byteAy.Length);
            return null;
        }

        int intCount = byteAy.Length >> 2;// 除4
        int[] intArray = new int[intCount];

        for (int i = 0; i < intCount; i++)
        {
            int val = 0;
            val |= byteAy[i * 4 + 3] << 24;
            val |= byteAy[i * 4 + 2] << 16;
            val |= byteAy[i * 4 + 1] << 8;
            val |= byteAy[i * 4];
            intArray[i] = val;
        }

        return intArray;
    }
}

public class ByteAyParserTester
{
    [Test]
    public void IsMatch()
    {
        int[] intAy = new int[] { -1, 0, 1, };
        byte[] bAy = ByteAyParser.IntAy2ByteAy(intAy);
        int[] intAyBack = ByteAyParser.ByteAy2IntAy(bAy);

        for (int i = 0; i < intAy.Length; i++)
        {
            if (intAy[i] != intAyBack[i])
            {
                Debug.LogErrorFormat("No Match intAy[{0}] {1} , intAyBack[{0}] {2}", i, intAy[i], intAyBack[i]);
                Assert.Fail();
            }
        }
    }

    [Test]
    public void IsMatchLimit()
    {
        int[] intAy = new int[] { int.MinValue, int.MinValue };
        byte[] bAy = ByteAyParser.IntAy2ByteAy(intAy);
        int[] intAyBack = ByteAyParser.ByteAy2IntAy(bAy);

        for (int i = 0; i < intAy.Length; i++)
        {
            if (intAy[i] != intAyBack[i])
            {
                Debug.LogErrorFormat("No Match intAy[{0}] {1} , intAyBack[{0}] {2}", i, intAy[i], intAyBack[i]);
                Assert.Fail();
            }
        }
    }
}