PowerShell Bitwise Operators


The following are powerShell bitwise operators.
Operator Description Expression Result
-band Bitwise AND 10 -band 3 2
-bor Bitwise OR (inclusive) 10 -bor 3 11
-bxor Bitwise OR (exclusive) 10 -bxor 3 9
-bnot Bitwise NOT -bNot 10 -11
-shl Shift-left 102 -shl 2 408
-shr Shift-right 102 -shr 1 51
Bitwise operators act on binary format of a value. In bitwise AND operation, the resulting bit is set to 1 when both input bit are 1.

1010 (10) 0011 ( 3) -------------- bAND 0010 ( 2)

In bitwise OR (inclusive) operation, the resulting bit is set to 1 when either or both input bit are 1. The resulting bit is set to 0 when both input bit are 0.

1010 (10) 0011 ( 3) -------------- bOR (inclusive) 1011 (11)

In bitwise OR (exclusive) operation, the resulting bit is set to 1 when only one input bit is 1.

1010 (10) 0011 ( 3) -------------- bXOR (exclusive) 1001 ( 9)

The bitwise NOT operator is unary operator that produce binary complement of a value. A bit of 0 is set to 1 and 1 is set to 0, for example binary complement of 0 is -1, maximum unsigned integer (0xfffffff), and the binary complement of -1 is 0.

0000 0000 0000 1010 (10) ------------------------- bNOT 1111 1111 1111 0101 (-11, xfffffff5)

In a bitwise shift-left operation, all bits are moved "n" places to the left, where "n" is the value of the right operand. A zero is inserted in the ones place. When the left operand is an Integer (32-bit) value, the lower 5 bits of the right operand determine how many bits of the left operand are shifted. When the left operand is a Long (64-bit) value, the lower 6 bits of the right operand determine how many bits of the left operand are shifted.
Expression Result Binary Result
21 -shl 0 21 0001 0101
21 -shl 1 42 0010 1010
21 -shl 2 84 0101 0100
In a bitwise shift-right operation, all bits are moved "n" places to the right, where "n" is specified by the right operand. The shift-right operator (-shr) inserts a zero in the left-most place when shifting a positive or unsigned value to the right. When the left operand is an Integer (32-bit) value, the lower 5 bits of the right operand determine how many bits of the left operand are shifted. When the left operand is a Long (64-bit) value, the lower 6 bits of the right operand determine how many bits of the left operand are shifted.
Expression Result Binary Hex
21 -shr 0 21 0001 0101 0x15
21 -shr 1 10 0000 1010 0x0A
21 -shr 2 5 0000 0101 0x05
21 -shr 31 0 0000 0000 0x00
21 -shr 32 21 0001 0101 0x15
21 -shr 64 21 0001 0101 0x15
21 -shr 65 10 0000 1010 0x0A
21 -shr 66 5 0000 0101 0x05
[int]::MaxValue -shr 1 1073741823 0x3FFFFFFF
[int]::MinValue -shr 1 -1073741824 0xC0000000
-1 -shr 1 -1 0xFFFFFFFF

Subscribe to receive free email updates:

3 Responses to "PowerShell Bitwise Operators"