字节数组 转 整型数 ,还有其他好办法?
byte[] mytest = new byte[4];
mytest[0]=0x01;
mytest[1]=0x02;
mytest[2]=0x03;
mytest[3]=0x04;
//实现4字节数组到整数的转换
b = mytest[3] + (mytest[2] << 8) + (mytest[1] << 16)+(mytest[0] << 24);
byte[] buffer = BitConverter.GetBytes(1000);
/// <summary>
/// 自定义结构转换为byte[]类型
/// </summary>
/// <param name="anything">自定义结构</param>
/// <returns>byte[]数组</returns>
public static byte[] RawSerialize(object anything)
{
int rawsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawdatas = new byte[rawsize];
Marshal.Copy(buffer, rawdatas, 0, rawsize);
Marshal.FreeHGlobal(buffer);
return rawdatas;
}
/// <summary>
/// byte[]结构转换为自定义结构
/// </summary>
/// <param name="rawdatas">源byte[]数组</param>
/// <param name="anytype">自定义结构类型</param>
/// <returns>自定义结构变量</returns>
public static object RawDeserialize(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length)
return null;
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawdatas, 0, buffer, rawsize);
object retobj = Marshal.PtrToStructure(buffer, anytype);
Marshal.FreeHGlobal(buffer);
return retobj;
}
没测试效率,供参考。
[解决办法]
我感觉还是LZ的效率比较高,我好像记得,移位操作对计算机底层硬件来说执行很快的
[解决办法]
b = mytest[3] + (mytest[2] << 8) + (mytest[1] << 16)+(mytest[0] << 24); 这种效率是最高的,用其他的就是浪费。