簡體   English   中英

C#將int轉換為2個字節的數組

[英]C# Converting an int into an array of 2 bytes

如果我的問題不夠清楚,我會提前道歉,我沒有使用c#的豐富經驗,並且遇到了一個奇怪的問題。 我正在嘗試將int轉換為兩個字節的數組(例如:取2210並獲取:0x08、0xA2),但是我得到的只是:0x00,0xA2,我不知道為什么。 非常感謝任何建議。 (我嘗試閱讀有關此問題的其他問題,但找不到有用的答案)

我的代碼:

        profile_number = GetProfileName(); // it gets the int 
        profile_num[0] = (byte) ((profile_number & 0xFF00));
        profile_num[1] = (byte) ((profile_number & 0x00FF));
        profile_checksum = CalcProfileChecksum();

//注意:我指的是2字節數組,因此有關4字節數組的問題的答案對我沒有幫助。

您需要移動第一個字節:

 //profile_num[0] = (byte) ((profile_number & 0xFF00));
 profile_num[0] = (byte) ((profile_number & 0xFF00) >> 8);
 profile_num[1] = (byte) ((profile_number & 0x00FF));

首先,我認為這是最簡單的方法:

public static byte[] IntToByteArray(int value)
{
    return (new BigInteger(value)).ToByteArray();
}

但是我意識到ToByteArray只返回需要的字節。 如果該值較小(小於256),則將返回一個字節。 我注意到的另一件事是,在返回的數組中取反了值,以便在左側找到右側的字節(最不重要的字節)。 因此,我進行了一些修訂:

public static byte[] IntToByteArrayUsingBigInteger(int value, int numberOfBytes)
    {
        var res = (new BigInteger(value)).ToByteArray().Reverse().ToArray();
        if (res.Length == numberOfBytes)
            return res;

        byte[] result = new byte[numberOfBytes];

        if (res.Length > numberOfBytes)
            Array.Copy(res, res.Length - numberOfBytes, result, 0, numberOfBytes);
        else
            Array.Copy(res, 0, result, numberOfBytes - res.Length, res.Length);

        return result;
    }

我知道這不能與按位運算的性能相提並論,而是為了學習新事物,並且如果您喜歡使用.NET提供的高級類而不是低級並使用按位運算符,我認為這是一個不錯的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM