Bitwise

From Xojo Documentation

Module

Performs bitwise operations on integers. The BitWise class supports operations on 64-bit integers. However, you can still pass 32-bit integers and work with the result as a 32-bit integer.

Methods
BitAnd OnesComplement
BitOr ShiftLeft
BitXor ShiftRight

Notes

You do not need to create an instance of the Bitwise class in order to access its methods. It is a special object, like System or Application, that always exists.

The And, Not, Or, and Xor operators are overloaded. They can be passed either booleans or integers. If they are passed integers, they perform the corresponding bitwise operators that are supported by the Bitwise class.

BitAnd

The BitAnd method returns a UInt64 that is the result of comparing each bit of the two integers passed (or contiguous integers passed if passing three or more integers) and assigning 1 to the bit position in the integer returned if both bits in the same position in the integer passed are 1. Otherwise, 0 is assigned to the bit position.

BitOr

The BitOr method returns a UInt64 that is the result of comparing each bit of the two integers passed (or contiguous integers passed if passing three or more integers) and assigning 1 to the bit position in the integer returned if either of the bits in the same position in the integers passed are 1. Otherwise, 0 is assigned to the bit position.

BitXor

The BitXor method returns a UInt64 that is the result of comparing each bit of the two integers passed (or contiguous integers passed if passing three or more integers) and assigning 1 to the bit position in the integer returned if both bits in the same position in the integers passed are not equal. Otherwise, 0 is assigned to the bit position.

The following table shows the results:

Integer1 Integer2 BitAnd BitOr BitXor
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

The And, Or, Xor, and Not operators are overloaded. They can perform both logical operations (when passed booleans) or bitwise operations when passed integers. In the latter case, they perform the same functions as the BitAnd, BitOr, and BitXor methods of the Bitwise class.

Ones complement is sometimes used to represent positive and negative numbers. Positive numbers start with zeros and negative numbers start with ones. The only problem is that zero is represented two ways:

Decimal Ones complement Signed Decimal
0 000 0
1 001 1
2 010 2
3 011 3
4 100 -3
5 101 -2
6 110 -1
7 111 -0

Sample Code

The following code performs BitAnd, BitOr, and BitXor operations on the passed integers.

Var i As Integer
i = Bitwise.BitAnd(5, 3) // returns 1
i = Bitwise.BitOr(5, 3) // returns 7
i = Bitwise.BitXor(5, 3) // returns 6

The following code illustrates how to re-express a bit expression that was written in C. The following expression in C:

(0xE0 | ((c >> 12) & 0x0F))

would become:

Bitwise.BitOr(&hE0, Bitwise.BitAnd(Bitwise.ShiftRight(c, 12), &h0F))

See Also

And, Not, Or, Xor operators