作者微信 bishe2022

代码功能演示视频在页面下方,请先观看;如需定制开发,联系页面右侧客服
C# int32与byte[] 互转 / C/C++ int与BYTE[]互转

Custom Tab



C#: 32位的int类型数据转换成4个字节的byte数据

  /// <summary>
        /// 把int32类型的数据转存到4个字节的byte数组中
        /// </summary>
        /// <param name="m">int32类型的数据</param>
        /// <param name="arry">4个字节大小的byte数组</param>
        /// <returns></returns>
        static bool ConvertIntToByteArray(Int32 m, ref byte[] arry)
        {
            if (arry == null) return false;
            if (arry.Length < 4) return false;

            arry[0] = (byte)(m & 0xFF);
            arry[1] = (byte)((m & 0xFF00) >> 8);
            arry[2] = (byte)((m & 0xFF0000) >> 16);
            arry[3] = (byte)((m >> 24) & 0xFF);

            return true;
        }


调用方法:


byte [] buf = new byte[4];
bool ok = ConvertIntToByteArray(0x12345678, ref buf);


这样就可以实现 32位的int类型数据转换成4个字节的byte数据了。

反过来的话,可以直接使用 BitConverter.ToInt32方法来实现:

   Int32 dd = BitConverter.ToInt32(buf, 0);

buf就是上面使用过的buf。



C/C++ 实现32位int数据与BYTE[]互转



int --> BYTE[]

int data = 0xFFFFFFFF;
	unsigned char buf[4];

	memcpy(buf, &data, sizeof(int));


BYTE[] --> int

memcpy(&data, buf, 4);




这个转换的实现不难,只要掌握了数据的存储格式就知道了。

特此mark一下!





转载自:http://blog.csdn.net/brantyou/article/details/18698647

Home