1. 程式人生 > >C# int32與byte[] 互轉 / C/C++ int與BYTE[]互轉

C# int32與byte[] 互轉 / C/C++ int與BYTE[]互轉

在某些時刻,我們需要對32位的int型別資料轉換成byte資料進行傳輸、儲存等。

這時,就需要把 32位的int型別資料轉存到 4個位元組的byte陣列中,或者是從4個位元組的byte陣列中轉存為32位的int型別資料。

在C/C++中,我們可以直接使用memcpy()函式來實現,但是在C#中卻沒有函式可以直接把 32位的int型別資料轉換成byte資料。

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一下!