 # Powershellish Arithmetic or why “Text”+2 not equal 2+”text” part2

In part one of my blog I discussed some drastic differences of Powershellish Arithmetic. Now we will start from the beginning and showcase all Arithmetic operators from Powershellish view.

### PowerShell Arithmetic Operators

There are total 11 arithmetic operators in Powershell.

All of the operators can be divided into two groups: Regular Operators (5) and Bitwise operators (6).

#### Regular operators

• +addition operator. Used to add values to each other. The main difference from regular Arithmetic operator is the ability to concatenate strings, arrays  and hash tables.
• subtraction operator, works the same way as in regular Arithmetic. Used to subtract values from each other. Also used to indicate negative number.
• * multiplication operator. Used to multiply values. Also in Powershell multiplication operator copy strings and arrays specified number of times.
• / division operator. Work the same way as in regular Arithmetic- divide two values.
• %modulus. Returns remainder of the division.

#### Bitwise operators

*only works on integer types
Bitwise operators compare each bit of the first operand to the corresponding bit of the second operand.

• band – Bitwise AND. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
• bnot – Bitwise NOT. Bits that are 0 become 1, and those that are 1 become 0.
• bor – Bitwise OR. The result in each position is 0 if both bits are 0, while otherwise the result is 1.
• bxor – Bitwise XOR. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.
• shl – Bitwise left shift. Shifts bits to the left for specified number of times.
• shr –  Bitwise right shift. Shifts bits to the right for specified number of times.

#### Precedence

The arithmetic operators in Powershell has the same precedence as in regular math.

Parentheses  () have the highest priority. Next one in priority hierarchy is negative number operator, then it is multiplication,division and modulus operators which have the same priority and the last but not least are addition and subtraction.

Just to sum up, PowerShell analyzes expressions from left to right according to the precedence rules.

1. Parentheses – priority 0
2. Negative number – priority 1
3. Multiplication, Division and modulus-priority 2
4. Addition and subtraction- priority 3

P.S. I also want to point out that Powershell had very interesting rounding rules. When result of the division is integer it is rounded to the closest integer. However, if the result is .5 (right in the middle) it is rounded to the nearest EVEN integer.

Thanks a lot for reading.

Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY

This site uses Akismet to reduce spam. Learn how your comment data is processed.