位移时为负数

negative number when bitshifting

好的,我有 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

经过这一切,这些是我得到的结果 输出 A = 255 outR = 255 输出 G = 0 outB = 255

首先,打开Option Strict(see also: 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

这里我们return一个UInt32,也把参数转成UInt32s,这样就不会溢出任何东西的最大值。 4294902015 大到放不下一个有符号的 32 位整数,所以我们改用一个无符号的 32 位整数来代替它。