xzhu
xzhu

Reputation: 49

Request for interpretation of one-line VBA code

The following code coverts a color value to a 3D RGB array

Function Decimal2RGB(color_val)
    Decimal2RGB = Array(color_val \ 256 ^ 0 And 255, color_val \ 256 ^ 1 And 255, color_val \ 256 ^ 2 And 255)
End Function

Another similar sub is

Sub Sample()
    Dim Col As Long

    '~~> RGB to LONG
    Col = RGB(255, 111, 254)

    Debug.Print Col

    '~~> LONG To RGB
    R = Col Mod 256
    G = (Col \ 256) Mod 256
    B = (Col \ 256 \ 256) Mod 256

    Debug.Print R
    Debug.Print G
    Debug.Print B
End Sub

My question is what does the "And" operator do in the first sub routine?

Execution example of the first sub: {=Decimal2RGB(258)} produces {2, 1, 0}.

Upvotes: 1

Views: 58

Answers (1)

iDevlop
iDevlop

Reputation: 25252

As Jeeped said, And is a bitwise operator in VBA.
So And 255 masks all bits higher than the 8th one. Eg:

455dec -> 111000111  
255dec -> 011111111  
And    -> 011000111 -> 199dec

Upvotes: 3

Related Questions