5

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?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Barun
  • 1,885
  • 3
  • 27
  • 47

3 Answers3

13

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

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
2

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.

Shog9
  • 156,901
  • 35
  • 231
  • 235
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
-4
result = YourVar AND cshort('0000000011111111')
bugtussle
  • 1,416
  • 11
  • 15
  • 2
    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 Oct 28 '10 at 19:34