Saturday, September 21, 2013

Visual Basic .NET - Binary Operations

In Visual Basic, I sometimes start missing Java's nice bit operators, especially when I really need to pack boolean data into a single number.  Fortunately, VB has this; it's just less intuitive.  The operator for logical functions is indistinguishable from that of bit functions.  So, I can just do this:

For x = 0 To 7
    ChecklistPunctuation.Items(x).Selected = ((t.Punctuation And 2 ^ x) <> 0)
Next

Less fortunately, VB does not have shift operators.  You can however make do with integer division, multiplication, and exponents of two.  To shift a collection of bits N to the left, do this:

shifted = (bitcol \ (2 ^ N))

Maybe it's true that the language wasn't intended to be used in advanced/professional environments, but it certainly has been tortured into providing pretty much any functionality you could want.

No comments:

Post a Comment