我遇到了一個我認爲應該是一個簡單解決方案的死衚衕。 基本上,我有:C#將2個Int16加入到Int32中
List<Uint16> header = new List<UInt16>();
然後,我用數據來填充它,但後來我需要加入幾個元素融入的Int32的,我不知道是什麼做的最好的方式。有沒有任何.NET的電話可以加入到Uint32中?
感謝
我遇到了一個我認爲應該是一個簡單解決方案的死衚衕。 基本上,我有:C#將2個Int16加入到Int32中
List<Uint16> header = new List<UInt16>();
然後,我用數據來填充它,但後來我需要加入幾個元素融入的Int32的,我不知道是什麼做的最好的方式。有沒有任何.NET的電話可以加入到Uint32中?
感謝
您可以使用Bitwise Operators:
uint num = (uint)((header.ElementAt(0) << 16) | header.ElementAt(1));
如果加入他們的行列,你的意思是使用一個標記Uint16作爲32位UINT的最低16位,另一個爲最高16位,那麼你可以使用逐位算術和移位。例如:
Uint16 u1;
Uint16 u2;
Uint32 = (Uint32)u1 << 16 | (Uint32)u2;
我想我們還需要照顧系統的字節順序。
Stored value: 0x00000001 In memory representation: Memory Address Low High 0 1 2 3 +------+------+------+------+ | 00 | 00 | 00 | 01 | Big Endian Representation +------+------+------+------+ stores the least significant byte in higher memory address. So we get 0 in lower address. Low High 0 1 2 3 +------+------+------+------+ | 01 | 00 | 00 | 00 | Little Endian Representation +------+------+------+------+ stores the least significant byte in lower memory address.
因此,如果我們需要粘貼2 uint16
那麼首先我們需要了解的字節順序。
uint16 val1, val2; val1 +------+------+ +------+------+ | b1 | b2 | OR | b2 | b1 | +------+------+ +------+------+ (paste) (paste) val2 +------+------+ +------+------+ | b3 | b4 | OR | b4 | b3 | +------+------+ +------+------+ ===============================+=============================== paste(val1,val2) | paste(val2,val1) 0 1 2 3 | 0 1 2 3 +------+------+------+------+ | +------+------+------+------+ | b1 | b2 | b3 | b4 | | | b4 | b3 | b2 | b1 | +------+------+------+------+ | +------+------+------+------+ val1 val2 | val2 val1 LITTLE Endian BIG Endian
因此需要考慮字節順序。
要檢查系統的Endinness可以使用
endian = (((char *)&x)[0]) ? 0 : 1;
哪裏0
是小和1
大。 (我在這裏沒有解釋這一點)。
根據此輸出,您可以使用paste
函數來粘貼uint16
。
爲了完整起見,我正在編寫粘貼功能。
uint32 paste (uint16 n1, uint16 n2)
{
return ((uint32) n1 << 16)| (uint) n2;
}
Function get_DWord(ByVal D1 As Short, ByVal D2 As Short) As Integer
Dim Bits As String = Convert.ToString(D1, 16)
Dim length As Integer = Bits.Length
If length < 4 Then
For I As Integer = 0 To 4 - length
Bits = "0" & Bits
Next
End If
Dim Bits2 As String = Convert.ToString(D2, 16)
Dim No As Integer = Convert.ToInt32(Bits2 & Bits, 2)
Return No
End Function
你所說的 「加盟」 是什麼意思? – DavidG 2015-02-06 15:59:35
我會使用「聯合」而不是「加入」(通常與數據庫「加入」操作相關聯) – 2015-02-06 16:04:24
基本上下面的人建議什麼。謝謝你看這個。 – SYB 2015-02-06 16:04:51