簡體   English   中英

C#將2個Int16連接到Int32

[英]C# join 2 Int16 into Int32

對於我認為應該是一個簡單的解決方案,我陷入了死胡同。 基本上,我有:

List<Uint16> header = new List<UInt16>();

然后,我用數據填充它,但是后來我需要將幾個元素加入Int32,我不知道什么是最好的方法。 我可以進行任何.NET調用來將這兩個加入Uint32嗎?

謝謝

您可以使用位移來做到這一點:

var num = (uint)((header.ElementAt(0) << 16) | header.ElementAt(1));

假設元素0為最高有效。

您可以使用按位運算符

    uint num = (uint)((header.ElementAt(0) << 16) | header.ElementAt(1));

我認為我們還需要注意系統的字節序。

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.

因此,如果我們需要粘貼兩個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;
}

如果通過加入它們來表示將一個Uint16用作32位Uint的最低16位,而另一個用作最高16位,則可以使用按位算術和移位。 就像是:

Uint16 u1;
Uint16 u2;
Uint32 = (Uint32)u1 << 16 | (Uint32)u2;
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

暫無
暫無

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

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