Bitwise Operator

From bibbleWiki
Jump to navigation Jump to search

Bitwise Operations Overview

Bitwise operations fall into three major groups:

  1. Bitwise Logic Operators
  2. Bitwise Shift Operators
  3. Bit Rotation Operators

These operations work directly on the binary representation of integers.

1. Bitwise Logic Operators

AND ( & )

A result bit is 1 only if both input bits are 1.

0b1100 & 0b1010 = 0b1000



OR ( | )

A result bit is 1 if either input bit is 1.

0b1100 | 0b1010 = 0b1110



XOR ( ^ )

A result bit is 1 if the input bits are different. A result bit is 0 if the input bits are the same.

0b1100 ^ 0b1010 = 0b0110

NOT ( ~ or ! )

1 becomes 0, and 0 becomes 1.

~0b00001111 = 0b11110000



2. Bitwise Shift Operators

(Arithmetic) Left Shift ( << )

Shifts the right hand side to the left n positions

0b0001 << 2 = 0b0100
(Arithmetic) Right Shift ( >> )

Shifts the left hand side to the right n positions

0b1000 >> 3 = 0b0001
Logical Right Shift ( >>> )
0b1000 >>> 3 = 0b0001

(Only in TypeScript/JavaScript)

3. Bit Rotation Operators

Rotate Left (ROL)
ROL(0b1001, 1) = 0b0011
Rotate Right (ROR)
ROR(0b1001, 1) = 0b1100

Note: Only Rust, C++20, and C# provide built‑in rotate functions.

Language Support Table

Operation Rust C C++ C# TypeScript
AND ( & )
)
XOR ( ^ )
NOT ( ~ / ! ) ! for ints ~ ~ ~ ~
Left Shift ( << )
Right Shift ( >> )
Logical Right Shift ( >>> )
Rotate Left rotate_left() std::rotl RotateLeft
Rotate Right rotate_right() std::rotr RotateRight

Language Notes

Rust

  • Right shift is arithmetic for signed integers, logical for unsigned.
  • Bitwise NOT uses ! instead of ~.
  • Provides built‑in rotate_left() and rotate_right().

C

  • Right shift of signed integers is implementation-defined.
  • No built‑in rotate operations.

C++

  • C++20 adds std::rotl and std::rotr.
  • Right shift of signed integers is implementation-defined (same as C).

C#

  • Right shift is arithmetic for signed, logical for unsigned.
  • Provides BitOperations.RotateLeft/Right.

TypeScript

  • Has both arithmetic (>>) and logical (>>>) right shift.
  • No built‑in rotate; must be implemented manually.