比特换档时的负数

时间:2015-07-28 10:33:56

标签: vb.net integer long-integer bit-shift

好的,我有4个值(A,R,G,B),我试图将它们变成小数。

public function MergeABGR(A, R, G, B)
Return (A << 24) + (R << 16) + (G << 8) + B
end function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
msgbox(MergeABGR(dim a = 255, dim r = 255, dim g = 0, dim b = 255))
End Sub

我从中得到的结果是:-65282。

我应该得到:4294902015

任何人都知道为什么会这样吗?

Dim Decimal as Long = 4294902015
Dim outA as integer = SplitA(Decimal, OutA)
Dim outR as integer = SplitR(Decimal, OutR)
Dim outG as integer = SplitG(Decimal, OutG)
Dim outB as integer = SplitB(Decimal, OutB)


Public Function SplitR(ABGR, ByRef R)

    R = ABGR And &HFF
    Return R
End Function
Public Function SplitG(ABGR, ByRef G)

    G = ABGR >> 8 And &HFF
    Return G
End Function

Public Function SplitB(ABGR, ByRef B)

    B = ABGR >> 16 And &HFF
    Return B
End Function

Public Function SplitA(ABGR, ByRef A)

    A = ABGR >> 24 And &HFF
    Return A
End Function

毕竟,这些是我得到的结果     outA = 255     outR = 255     outG = 0     outB = 255

1 个答案:

答案 0 :(得分:1)

首先,打开Option Strict(另请参阅:what's an option strict and explicit?),因此您必须为所有内容定义类型。从长远来看,这是值得的。

现在我们必须为所有内容创建类型,您的函数可能如下所示:

Public Function MergeABGR(A as Byte, R as Byte, G as Byte, B as Byte) as UInt32
    Return (Convert.ToUInt32(A) << 24) + (Convert.ToUInt32(R) << 16) + (Convert.ToUInt32(G) << 8) + B
End Function

我们返回UInt32的位置,并将参数转换为UInt32 s,这样我们就不会溢出任何值的最大值。 4294902015足够大,不适合带符号的32位整数,所以我们切换到无符号的32位整数来代替它。