Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a bitwise-AND operation in VB.NET?

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?

like image 892
Barun Avatar asked Oct 28 '10 19:10

Barun


2 Answers

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

like image 169
Shog9 Avatar answered Oct 22 '22 06:10

Shog9


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.

like image 32
Guffa Avatar answered Oct 22 '22 06:10

Guffa