views:

70

answers:

3

I want to perform a bitwise-AND operation in VB.NET, taking a Short (16-bit) variable and ANDing it with '0000000011111111' (thereby retaining only the least-significant byte / 8 least-significant bits).

How can I do it?

+3  A: 

0000000011111111 represented as a VB hex literal is &HFF (or &H00FF if you want to be explicit), and the ordinary AND operator is actually a bitwise operator. So to mask off the top byte of a Short you'd write:

shortVal = shortVal AND &HFF

For more creative ways of getting a binary constant into VB, see: VB.NET Assigning a binary constant

Shog9
Barun
@Barun: the leading 0s are superfluous. Use 'em if you want to... It makes no difference.
Shog9
+2  A: 

Use the And operator, and write the literal in hexadecimal (easy conversion from binary):

theShort = theShort And &h00ff

If what you are actually trying to do is to divide the short into bytes, there is a built in method for that:

Dim bytes As Byte() = BitConverter.GetBytes(theShort)

Now you have an array with two bytes.

Guffa
A: 

result = YourVar AND cshort('0000000011111111')

bugtussle
Strings are delimited with quotation marks not apostrophes. The CShort function doesn't assume binary as base, but decimal, so trying to convert that string causes an overflow.
Guffa