在VB.NET中,按位移位操作提供32位结果而不是64位结果

时间:2013-07-06 06:23:30

标签: vb.net bitwise-operators bit-shift

当我将两个32位整数组合时,它应该形成一个64位长整数,但它保持32位负值。怎么了?

仅此一行应生成大于32位的数字:(readDword() And &HFFFFFFFF) << 32)

用于测试的VB.NET代码

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim u As Long = ((readDword() And &HFFFFFFFF) << 32) Or _
        (readDword2() And &HFFFFFFFF)
End Sub

Function readDword() As Integer
    Dim i As Integer = (((0 And &HFF) << 24) Or _
((0 And &HFF) << 16) Or _
((11 And &HFF) << 8) Or _
(58 And &HFF))
    Return i
End Function

Function readDword2() As Integer
    Dim i As Integer = (((241 And &HFF) << 24) Or _
((145 And &HFF) << 16) Or _
((136 And &HFF) << 8) Or _
(247 And &HFF))
    Return i
End Function



预期结果
-----------------------------
输入字节= 0,0,11,58,241,145,136,247
结果我得到= -242119681
预期结果= 12347788855543
------------------------------


这可以正常使用,但它是向后的,所以我尝试按位自己做

    Dim bytesz() As Byte = New Byte() {247, 136, 145, 241, 58, 11, 0, 0}
    Dim a As Int64 = BitConverter.ToInt64(bytesz, 0)

如何用Java编写字节

  public void writeQWord(long l) throws IOException {
    write((int) (l >> 56)); //0
    write((int) (l >> 48)); //0
    write((int) (l >> 40)); //11
    write((int) (l >> 32)); //58
    write((int) (l >> 24)); //241
    write((int) (l >> 16)); //145
    write((int) (l >> 8));  //136
    write((int) (l));   }   //247

固定

正确的代码是:

Public Function ReadQWord() As Long
    Return (CLng(ReadDWord() And &HFFFFFFFFL) << 32) Or CLng(ReadDWord() And &HFFFFFFFFL)
End Function

1 个答案:

答案 0 :(得分:1)

使用按位运算符和常量时,请确保常量类型反映了您的用法。

    Dim u As Long = 1 << 32

和这个

    Dim u As Long = 1L << 32

产生不同的结果。我还注意到你的函数readDword只产生一个整数作为返回和内部。