日期:2014-05-17  浏览次数:21230 次

字节数组 转 整型数 ,还有其他好办法?
 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); 


刚试了,可以用

有没有更好的办法? 也就效率更好的? 如 联合体 C里可以

或者有这样的函数

byte[] buffer = BitConverter.GetBytes(1000);


当然,这个函数是反向的,即 整数 转到 字节数组...

有反向的函数么? 



------解决方案--------------------
BitConverter.GetInt32(字节, 0)
------解决方案--------------------
引用:
Quote: 引用:

BitConverter.ToInt32(字节, 0) 


可以用,,但是,字节数组的内容,要倒过来写...

原来是16进制数: 0x01020304  ,要倒过来存

即数 索引 0 里存04

1 里存03...



Array.Reverse(数组)
------解决方案--------------------

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