首先声明下:数组元素类型都是基础数据类型,比如:int[] i=new int[64];
请问:如何将i的内容放到一个byte数组中?反之如何将一个byte数组中的信息写到i中?

解决方案 »

  1.   


    int[] i = new int[64];
    byte[] bytes = new byte[ i.Length * 4 ];
    GCHandle gch = GCHandle.Alloc(i, GCHandleType.Pinned);
    Marshal.Copy(gch.AddrOfPinnedObject(), bytes, 0, bytes.Length);   //<-- 反之亦然
    gch.Free();
      

  2.   

    //uint to byte[]
    public static byte[] WriteUint(uint nValue)
            {
                byte[] bArray = new byte[4];
                bArray[3] = (byte)(nValue & 0xFF);
                bArray[2] = (byte)((nValue >> 8) & 0xFF);
                bArray[1] = (byte)((nValue >> 16) & 0xFF);
                bArray[0] = (byte)((nValue >> 24) & 0xFF);
                return bArray;
            }
    //byte[] to uint
    public uint ReadUint(byte[] a)
            {
                byte[] bArray = new byte[4];
                bArray = a;
                uint nValue = 0;
                nValue ^= bArray[0];
                nValue = nValue << 8;
                nValue ^= bArray[1];
                nValue = nValue << 8;
                nValue ^= bArray[2];
                nValue = nValue << 8;
                nValue ^= bArray[3];
                return nValue;
            }
      

  3.   

    非常感谢各位新老朋友的回贴!对于元素是基础数据类型的数组来说,Buffer.BlockCopy 是最佳方法!
    分不多,还请各位今后继续关照