日期:2014-05-18  浏览次数:20734 次

一维数组和字节数组转换
首先声明下:数组元素类型都是基础数据类型,比如:

int[] i=new int[64];


请问:如何将i的内容放到一个byte数组中?反之如何将一个byte数组中的信息写到i中?


------解决方案--------------------
循环赋值?
------解决方案--------------------
定义一个byte数组,循环赋值
------解决方案--------------------
我能想到的就是按位移动、与或操作等方法,抛砖引玉学习高人方法。
------解决方案--------------------
BitConverter
------解决方案--------------------
C# code

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();

------解决方案--------------------
BitConverter.ToInt32
------解决方案--------------------
BitConverter.GetBytes

------解决方案--------------------
Buffer.BlockCopy
------解决方案--------------------
探讨
Buffer.BlockCopy

------解决方案--------------------
好像可用的方法都让你们说完了
------解决方案--------------------
//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;
}