thumbnail

Bitwise and Shift Operators in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Bitwise Operators

Bitwise operators are useful for manipulating individual bits of number in Dart.

Operator Description
| OR
& AND
~expr Bitwise complement 1s become 0s, 0s become 1s
^ XOR

Bitwise shift operators in Dart

Shift operators help you to shift binary bits of an integer to left or right as shown in folliwng table.

Operator Description
» Shift right
« Shift left

Program that demonstrates use of Bitwise and Shift operators in Dart

void printBinary(int input) {
  int bin = 0, i = 1;
  while (input > 0) {
    bin = bin + (input % 2) * i;
    input = (input / 2).floor();
    i = i * 10;
  }

  print(bin);
}

main(List<String> args) {
  const a = 1; // binary representation: 1
  const b = 2; // binary representation: 10
  const c = 16; // binary representation: 1000

  printBinary(a << 4); // shift a by 4 bits to the left outputs 10000 in binary
  printBinary((c >> 4)); // shifts right by 4 bits making c = 1 in binary
  printBinary(
      (a & b)); // performs and operation on binary representation of a and b
  printBinary(
      (a & ~b)); // performs unary not operation on binary representation of b
  printBinary((a | b)); // or
  printBinary((a ^ b)); // xor
}

Above program produces following output:

10000
1
0
1
11
11

We hope that you have found this guide useful for learning how bitwise operators work in Dart.