microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
samples/language/BitwiseOperators.qs
71lines · modecode
| 1 | /// # Sample |
| 2 | /// Bitwise Operators |
| 3 | /// |
| 4 | /// # Description |
| 5 | /// Bitwise operators in Q# perform operations on the bits of integer values, |
| 6 | /// producing a new integer value. The bitwise operators in Q# are |
| 7 | /// `~~~`, `&&&`, `|||`, `^^^`, `>>>`, and `<<<`. |
| 8 | namespace MyQuantumApp { |
| 9 | |
| 10 | @EntryPoint() |
| 11 | operation Main() : Unit { |
| 12 | |
| 13 | // `~~~` performs a bitwise NOT on the bits of an integer. |
| 14 | |
| 15 | // The integer value -6. |
| 16 | let integer = ~~~5; |
| 17 | |
| 18 | // The integer value 4. |
| 19 | let integer = ~~~-5; |
| 20 | |
| 21 | // `&&&` performs a bitwise AND on the bits of two integer. |
| 22 | |
| 23 | // The integer value 4. |
| 24 | let integer = 5 &&& 6; |
| 25 | |
| 26 | // The integer value 2. |
| 27 | let integer = -5 &&& 6; |
| 28 | |
| 29 | // `|||` performs a bitwise OR on the bits of two integer. |
| 30 | |
| 31 | // The integer value 7. |
| 32 | let integer = 5 ||| 6; |
| 33 | |
| 34 | // The integer value -1. |
| 35 | let integer = -5 ||| 6; |
| 36 | |
| 37 | // `^^^` performs a bitwise XOR on the bits of two integer. |
| 38 | |
| 39 | // The integer value 3. |
| 40 | let integer = 5 ^^^ 6; |
| 41 | |
| 42 | // The integer value -3. |
| 43 | let integer = -5 ^^^ 6; |
| 44 | |
| 45 | // `>>>` performs a signed right bit-shift of a magnitude specified by the |
| 46 | // right-hand integer on the bits of the left-hand integer. |
| 47 | // If the right-hand integer is negative, it reverses the direction of the bit-shift. |
| 48 | |
| 49 | // The integer value 1. |
| 50 | let integer = 5 >>> 2; |
| 51 | |
| 52 | // The integer value -2. |
| 53 | let integer = -5 >>> 2; |
| 54 | |
| 55 | // The integer value 20. |
| 56 | let integer = 5 >>> -2; |
| 57 | |
| 58 | // `<<<` performs a signed left bit-shift of a magnitude specified by the |
| 59 | // right-hand integer on the bits of the left-hand integer. |
| 60 | // If the right-hand integer is negative, it reverses the direction of the bit-shift. |
| 61 | |
| 62 | // The integer value 20. |
| 63 | let integer = 5 <<< 2; |
| 64 | |
| 65 | // The integer value -20. |
| 66 | let integer = -5 <<< 2; |
| 67 | |
| 68 | // The integer value 1. |
| 69 | let integer = 5 <<< -2; |
| 70 | } |
| 71 | } |
| 72 | |