C#/C++ 中字節數組與int類型轉換


1.C#中int和byte[]轉換:

/// <summary>
/// 把int32類型的數據轉存到4個字節的byte數組中
/// </summary>
/// <param name="m">int32類型的數據
/// <param name="arry">4個字節大小的byte數組
public 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;
}

/// <summary>
/// 把byte數組中的前4個字節轉換為int32類型的數據
/// </summary>
public static int ConvertByteArrayToInt(byte[] arry)
{
    return BitConverter.ToInt32(arry, 0);
}

 

2.C++中byte[]與int類型轉換

//int --> BYTE[]:

int data = 0xFFFFFFFF;
unsigned char buf[4];
 
memcpy(buf, &data, sizeof(int));

//BYTE[] --> int :

memcpy(&data, buf, 4);

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM