Bit manipulation

suggest change

Bit manipulation means treating an integer as a row of bits: testing and setting individual bits, packing several small values into one number, storing a set of flags in a single int, and doing fixed-width arithmetic for hashes, checksums and random number generators.

Dart's bitwise operators (&, |, ^, ~, <<, >>, >>>) and their precedence are introduced in Operators. Reading and writing bytes, ByteData, byte order and varints are covered in Bytes and binary data. This article builds on both and covers:

On native platforms (the Dart VM, AOT-compiled executables, Flutter on mobile and desktop) and with dart2wasm, int is a 64-bit two's complement integer. When compiled to JavaScript it is not, which is the subject of the last section. The examples were run with Dart 3.13.

Binary literals and printing bits

Dart has hex literals (0xA5) but no binary or octal literals. Parse a string with radix: 2 when a binary constant reads better, and use toRadixString(2) to print one:

String bin(int value, [int width = 8]) =>
    value.toUnsigned(width).toRadixString(2).padLeft(width, '0');

void main() {
  // Dart has no 0b literals: use hex, or parse a binary string.
  final mask = int.parse('1010_0101'.replaceAll('_', ''), radix: 2);
  print(mask);
  print(0xA5 == mask);
  print(0xFF_FF); // digit separators work in hex literals

  print(bin(0xA5));
  print(bin(5, 16));
  print(bin(-1)); // two's complement, 8 bits
  print(bin(-128));

  // toRadixString on a negative number prints a minus sign, not the bits.
  print((-6).toRadixString(2));
  print((-6).toRadixString(16));

  // For the full 64-bit pattern of a negative int, go through BigInt.
  print(BigInt.from(-6).toUnsigned(64).toRadixString(16));
}

Output:

165
true
65535
10100101
0000000000000101
11111111
10000000
-110
-6
fffffffffffffffa

toUnsigned(width) keeps the low width bits and makes them non-negative, so the bin helper shows the two's complement pattern of negative numbers for any width up to 63. toRadixString alone prints a minus sign and the magnitude, which is rarely what you want when looking at bits. For all 64 bits of a negative int, convert to BigInt first.

Hex literals accept _ digit separators (0xFF_FF, 0x8000_0000), which help with long masks.

Testing, setting, clearing and toggling bits

The four basic operations are one-liners. Wrapping them in an extension on int makes call sites read better:

extension BitOps on int {
  bool isBitSet(int n) => (this >> n) & 1 == 1;
  int setBit(int n) => this | (1 << n);
  int clearBit(int n) => this & ~(1 << n);
  int toggleBit(int n) => this ^ (1 << n);
  int withBit(int n, bool on) => on ? setBit(n) : clearBit(n);
}

String bin(int value, [int width = 8]) =>
    value.toUnsigned(width).toRadixString(2).padLeft(width, '0');

void main() {
  var x = 0x50; // 0101 0000
  print(bin(x));
  print(x.isBitSet(4));
  print(x.isBitSet(5));
  x = x.setBit(0);
  print(bin(x));
  x = x.clearBit(6);
  print(bin(x));
  x = x.toggleBit(7).toggleBit(4);
  print(bin(x));
  print(bin(x.withBit(1, true)));

  // In Dart, & binds tighter than ==, unlike C and Java.
  print(6 & 1 == 0);
}

Output:

01010000
true
false
01010001
00010001
10000001
10000011
true

Bits are numbered from 0 at the least significant (rightmost) end. int is immutable, so setBit and friends return a new value; assign it back.

The last line shows a precedence difference from C, C++ and JavaScript: in Dart the bitwise operators bind tighter than ==, !=, < and >. x & 1 == 0 means (x & 1) == 0, which is what you almost always want. Adding the parentheses anyway costs nothing and helps readers coming from other languages.

Masks and bit fields

A mask selects some bits: (1 << n) - 1 has the lowest n bits set. Shifting a value right and masking it reads a bit field; clearing the field and or-ing in a new value writes it.

The example uses the 16-bit date format of MS-DOS and ZIP files, which packs a year (7 bits), month (4 bits) and day (5 bits) into one number, and a 32-bit ARGB color:

/// A mask with the lowest [width] bits set, for width 0..63.
int lowMask(int width) => (1 << width) - 1;

/// Reads [width] bits of [value] starting at bit [shift].
int getField(int value, int shift, int width) =>
    (value >> shift) & lowMask(width);

/// Returns [value] with [width] bits at [shift] replaced by [field].
int setField(int value, int shift, int width, int field) {
  final mask = lowMask(width) << shift;
  return (value & ~mask) | ((field << shift) & mask);
}

// MS-DOS / ZIP date: bits 15-9 year since 1980, 8-5 month, 4-0 day.
int packDosDate(DateTime d) =>
    ((d.year - 1980) << 9) | (d.month << 5) | d.day;

DateTime unpackDosDate(int v) => DateTime(
      getField(v, 9, 7) + 1980,
      getField(v, 5, 4),
      getField(v, 0, 5),
    );

void main() {
  print(lowMask(4).toRadixString(2));
  print(lowMask(12).toRadixString(16));

  final date = packDosDate(DateTime(2026, 10, 17));
  print('0x${date.toRadixString(16)}');
  print(unpackDosDate(date));

  // Change only the day field.
  final moved = setField(date, 0, 5, 31);
  print(unpackDosDate(moved));

  // A value that is too wide is cut to the field width, not spilled
  // into the neighbouring field.
  print(unpackDosDate(setField(date, 0, 5, 33)));

  // 32-bit ARGB color, as used by Flutter's Color.
  const argb = 0xFF336699;
  final a = getField(argb, 24, 8), r = getField(argb, 16, 8);
  final g = getField(argb, 8, 8), b = getField(argb, 0, 8);
  print('a=$a r=$r g=$g b=$b');
  final halfAlpha = setField(argb, 24, 8, 0x80);
  print(halfAlpha.toRadixString(16));
}

Output:

1111
fff
0x5d51
2026-10-17 00:00:00.000
2026-10-31 00:00:00.000
2026-10-01 00:00:00.000
a=255 r=51 g=102 b=153
80336699

setField masks the new value with & mask, so a value that is too large is truncated instead of corrupting the neighbouring field. Whether silent truncation or an ArgumentError is better depends on where the data comes from; for user input, validate the range first.

When you pack values into a Uint8List or Uint16List, the typed list masks for you on assignment. With plain int you must do it yourself, because Dart's int doesn't overflow at 8, 16 or 32 bits.

Flags

A set of yes/no options fits in one int, one bit per option. This is compact, cheap to copy and compare, and matches C APIs (through dart:ffi) and binary file formats that store flags this way.

Use static const fields when the bit values are fixed by an external format. When the flags are your own, an enum with 1 << index avoids keeping the numbers in sync by hand:

// Flags as plain int constants, e.g. matching a C API or a file format.
abstract final class OpenFlags {
  static const read = 1 << 0;
  static const write = 1 << 1;
  static const create = 1 << 2;
  static const truncate = 1 << 3;
  static const append = 1 << 4;
}

String describe(int flags) {
  final names = <String>[];
  if (flags & OpenFlags.read != 0) names.add('read');
  if (flags & OpenFlags.write != 0) names.add('write');
  if (flags & OpenFlags.create != 0) names.add('create');
  if (flags & OpenFlags.truncate != 0) names.add('truncate');
  if (flags & OpenFlags.append != 0) names.add('append');
  return names.join('|');
}

// Flags from an enum: each value's bit is 1 << index.
enum Permission { read, write, execute, admin }

extension PermissionMask on Iterable<Permission> {
  int toMask() => fold(0, (mask, p) => mask | (1 << p.index));
}

Set<Permission> permissionsFrom(int mask) => {
      for (final p in Permission.values)
        if (mask & (1 << p.index) != 0) p,
    };

void main() {
  var flags = OpenFlags.write | OpenFlags.create | OpenFlags.truncate;
  print(describe(flags));

  // Has all of / has any of.
  const readWrite = OpenFlags.read | OpenFlags.write;
  print(flags & readWrite == readWrite);
  print(flags & readWrite != 0);

  flags |= OpenFlags.read; // add
  flags &= ~OpenFlags.truncate; // remove
  flags ^= OpenFlags.append; // toggle
  print(describe(flags));

  final mask = {Permission.read, Permission.execute}.toMask();
  print(mask);
  print(permissionsFrom(mask));
  print(permissionsFrom(0xF));
}

Output:

write|create|truncate
false
true
read|write|create|append
5
{Permission.read, Permission.execute}
{Permission.read, Permission.write, Permission.execute, Permission.admin}

The idioms are:

Deriving the bit from index means that reordering or inserting enum values changes the numbers. That's fine for masks that live only in memory, but if the mask is saved to disk or sent over the network, give each enum value an explicit bit as a field (enum Permission { read(1), write(2), ... }) so the format stays stable. Inside your own code, a Set<Permission> (see Creating a new Set) is clearer than a mask and usually fast enough; convert to and from the mask only at the boundary.

Bit tricks

Two's complement arithmetic gives some useful identities:

int has bitLength built in, but no population count or trailing-zero count, so we write them:

/// Number of set bits (population count), for non-negative values.
int popCount(int x) {
  var count = 0;
  while (x != 0) {
    x &= x - 1; // clears the lowest set bit
    count++;
  }
  return count;
}

bool isPowerOfTwo(int x) => x > 0 && (x & (x - 1)) == 0;

/// Smallest power of two >= x, for 1 <= x <= 2^62.
int nextPowerOfTwo(int x) => x <= 1 ? 1 : 1 << (x - 1).bitLength;

/// Index of the lowest set bit, or -1 for 0.
int trailingZeros(int x) => x == 0 ? -1 : (x & -x).bitLength - 1;

/// Indexes of all set bits, lowest first.
Iterable<int> setBits(int x) sync* {
  while (x != 0) {
    final low = x & -x;
    yield low.bitLength - 1;
    x ^= low;
  }
}

void main() {
  const x = 0x2C; // 0010 1100
  print('bitLength       ${x.bitLength}');
  print('popCount        ${popCount(x)}');
  print('lowest set bit  ${x & -x}');
  print('clear lowest    ${(x & (x - 1)).toRadixString(2)}');
  print('highest set bit ${1 << (x.bitLength - 1)}');
  print('trailing zeros  ${trailingZeros(x)}');
  print('set bits        ${setBits(x).toList()}');

  print([0, 1, 6, 64, 96].map(isPowerOfTwo).toList());
  print([1, 5, 64, 65, 1000].map(nextPowerOfTwo).toList());

  // Opposite signs without multiplication (which could overflow).
  print(((-5) ^ 7) < 0);

  // All subsets of {a, b, c}: count from 0 to 2^n - 1.
  const items = ['a', 'b', 'c'];
  for (var m = 0; m < 1 << items.length; m++) {
    final subset = [for (final i in setBits(m)) items[i]];
    print('${m.toRadixString(2).padLeft(3, '0')} $subset');
  }
}

Output:

bitLength       6
popCount        3
lowest set bit  4
clear lowest    101000
highest set bit 32
trailing zeros  2
set bits        [2, 3, 5]
[false, true, false, true, false]
[1, 8, 64, 128, 1024]
true
000 []
001 [a]
010 [b]
011 [a, b]
100 [c]
101 [a, c]
110 [b, c]
111 [a, b, c]

The popCount loop (Kernighan's method) runs once per set bit rather than once per bit. setBits is a sync* generator that uses the same idea to yield bit positions, and counting from 0 to 2^n - 1 visits every subset of n items, a common way to brute-force small combinatorial problems.

These helpers are written for non-negative values. On native platforms a negative int has 64 bits set from the sign extension, so popCount(-1) is 64, while bitLength of a negative number counts bits excluding the sign ((-256).bitLength is 8).

Fixed-width arithmetic

Code ported from C, Java or Go often relies on 8, 16 or 32-bit integers that wrap around. Dart has a single int type, so emulate the width explicitly:

int rotl32(int x, int n) {
  n &= 31;
  return ((x << n) | (x.toUnsigned(32) >>> (32 - n))).toUnsigned(32);
}

int rotr32(int x, int n) => rotl32(x, 32 - (n & 31));

/// Reverses the byte order of a 32-bit value.
int bswap32(int x) =>
    ((x & 0xFF) << 24) |
    ((x & 0xFF00) << 8) |
    ((x >> 8) & 0xFF00) |
    ((x >> 24) & 0xFF);

void main() {
  // Interpret the low n bits as unsigned or two's complement signed.
  print(0x1FF.toUnsigned(8));
  print(0xFF.toSigned(8));
  print(0x7F.toSigned(8));
  print((-1).toUnsigned(16));
  print(0xFFFE.toSigned(16));

  // Sign-extend a 12-bit field read from a sensor register.
  const raw = 0xF38; // 12 bits
  print(raw.toSigned(12));

  // Native int arithmetic wraps around at 64 bits.
  const max = 0x7FFFFFFFFFFFFFFF;
  print(max + 1);
  print(max * 2);

  // Emulate 32-bit unsigned arithmetic by masking after each step.
  print((0xFFFFFFFF + 1).toUnsigned(32));
  print((0x80000000 * 2) & 0xFFFFFFFF);

  print(rotl32(0x80000001, 1).toRadixString(16));
  print(rotr32(0x12345678, 8).toRadixString(16));
  print(bswap32(0x12345678).toRadixString(16));
}

Output:

255
-1
127
65535
-2
-200
-9223372036854775808
-2
0
0
3
78123456
78563412

Native int arithmetic wraps around silently at 64 bits: max + 1 is the smallest negative number and no exception is thrown. Use BigInt when you need more than 64 bits.

rotl32 converts to unsigned before the >>> so that a negative input doesn't shift ones from bit 63 into the result, and masks n to 0..31. Shifting by 64 or more is allowed and gives 0 (or -1 for >> of a negative number), but shifting by a negative amount throws an ArgumentError.

For whole byte sequences, converting byte order with ByteData and Endian (see Bytes and binary data) is clearer than bswap32.

A compact BitSet

A List<bool> stores a reference per element, 4 or 8 bytes each. Packing the flags into a Uint32List needs one bit per element, and operations like intersection process 32 elements at a time. The index i lives in word i >> 5 (i / 32) at bit i & 31 (i % 32):

import 'dart:typed_data';

/// A fixed-size set of bits packed into 32-bit words.
/// 32-bit words keep it correct when compiled to JavaScript.
class BitSet {
  BitSet(this.length) : _words = Uint32List((length + 31) >> 5);

  final int length;
  final Uint32List _words;

  bool operator [](int i) {
    RangeError.checkValidIndex(i, this, 'index', length);
    return _words[i >> 5] & (1 << (i & 31)) != 0;
  }

  void operator []=(int i, bool value) {
    RangeError.checkValidIndex(i, this, 'index', length);
    if (value) {
      _words[i >> 5] |= 1 << (i & 31);
    } else {
      _words[i >> 5] &= ~(1 << (i & 31));
    }
  }

  void setAll() {
    _words.fillRange(0, _words.length, 0xFFFFFFFF);
    final extra = length & 31; // clear bits past the end
    if (extra != 0) _words[_words.length - 1] = (1 << extra) - 1;
  }

  int get cardinality {
    var n = 0;
    for (var w in _words) {
      while (w != 0) {
        w &= w - 1;
        n++;
      }
    }
    return n;
  }

  void intersect(BitSet other) {
    for (var i = 0; i < _words.length; i++) {
      _words[i] &= other._words[i];
    }
  }

  Iterable<int> get indexes sync* {
    for (var wi = 0; wi < _words.length; wi++) {
      var w = _words[wi];
      while (w != 0) {
        final low = w & -w;
        yield (wi << 5) + low.bitLength - 1;
        w ^= low;
      }
    }
  }
}

/// Sieve of Eratosthenes: one bit per number instead of one bool.
BitSet primesBelow(int n) {
  final sieve = BitSet(n)..setAll();
  sieve[0] = false;
  sieve[1] = false;
  for (var i = 2; i * i < n; i++) {
    if (!sieve[i]) continue;
    for (var j = i * i; j < n; j += i) {
      sieve[j] = false;
    }
  }
  return sieve;
}

void main() {
  final primes = primesBelow(1000000);
  print(primes.cardinality);
  print(primes.indexes.take(10).toList());
  print(primes[999983]);

  final odd = BitSet(100);
  for (var i = 1; i < 100; i += 2) {
    odd[i] = true;
  }
  final small = primesBelow(100)..intersect(odd);
  print(small.indexes.toList());
}

Output:

78498
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
true
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

The sieve stores a million flags in 125 KB. The class uses 32-bit words on purpose: it gives the same results when compiled to JavaScript, where bitwise operations are limited to 32 bits. On native platforms only, you could use a Uint64List and 1 << (i & 63) to halve the number of words. The Operators article shows how operator [] and operator []= work.

Bit operations on the web

When Dart is compiled to JavaScript with dart compile js (or webdev/flutter build web without --wasm), int is a JavaScript number: a 64-bit floating point value that holds integers exactly only up to 2^53. Bitwise operators are implemented with JavaScript's, which work on 32 bits:

With dart2wasm (dart compile wasm, flutter build web --wasm) int is a real 64-bit integer, so the results match the VM.

Here is the same program run on the Dart VM, compiled to JavaScript and to WebAssembly, both run with Node.js. The values are read from a list so that the compiler can't compute the results at compile time:

void main(List<String> args) {
  // Read the values at run time so the compiler can't fold them.
  final v = [0, -1, 1, -16, 0x123456789, 0xFFFFFFFF, 0x80000000];
  final zero = v[0], minus1 = v[1], one = v[2], m16 = v[3];
  final big = v[4], u32max = v[5], hi = v[6];
  print('~0          ${~zero}');
  print('-1 & 0xFF   ${minus1 & 0xFF}');
  print('1 << 31     ${one << 31}');
  print('1 << 32     ${one << 32}');
  print('-16 >> 2    ${m16 >> 2}');
  print('-16 >>> 2   ${m16 >>> 2}');
  print('big | 0     ${big | 0}');
  print('big & ~0xF  ${big & ~0xF}');
  print('big >> 4    ${big >> 4}');
  print('u32max ^ 1  ${u32max ^ 1}');
  print('hi          ${hi.toSigned(32)}');
  print('big ~/ 16   ${big ~/ 16}');
  print('1.0 is int  ${(1.0 as Object) is int}');
}

Dart VM and WebAssembly (identical output):

~0          -1
-1 & 0xFF   255
1 << 31     2147483648
1 << 32     4294967296
-16 >> 2    -4
-16 >>> 2   4611686018427387900
big | 0     4886718345
big & ~0xF  4886718336
big >> 4    305419896
u32max ^ 1  4294967294
hi          -2147483648
big ~/ 16   305419896
1.0 is int  false

JavaScript:

~0          4294967295
-1 & 0xFF   255
1 << 31     2147483648
1 << 32     0
-16 >> 2    4294967292
-16 >>> 2   1073741820
big | 0     591751049
big & ~0xF  591751040
big >> 4    36984440
u32max ^ 1  4294967294
hi          -2147483648
big ~/ 16   305419896
1.0 is int  true

Every line involving negative numbers, bits above 31, or ~ differs. big & ~0xF silently drops the top bit of a 33-bit number, and 1.0 is int is true because JavaScript has no separate integer type.

Writing portable bit code

If your code must give the same answers on native platforms and in JavaScript, follow these rules:

The 32-bit FNV-1a hash shows the multiplication problem. The naive version multiplies a 32-bit hash by a 25-bit prime, a product of up to 57 bits:

import 'dart:convert';

/// 32-bit multiply that gives the same result on the VM and the web:
/// split [a] so no intermediate product exceeds 2^53.
int mul32(int a, int b) {
  final aLo = a & 0xFFFF, aHi = (a >>> 16) & 0xFFFF;
  return (aLo * b + (((aHi * b) & 0xFFFF) << 16)) & 0xFFFFFFFF;
}

int fnv1aNaive(List<int> bytes) {
  var h = 0x811C9DC5;
  for (final b in bytes) {
    h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF; // product can exceed 2^53
  }
  return h;
}

int fnv1a(List<int> bytes) {
  var h = 0x811C9DC5;
  for (final b in bytes) {
    h = mul32(h ^ b, 0x01000193);
  }
  return h;
}

int rotl32(int x, int n) {
  n &= 31;
  return ((x << n) | (x.toUnsigned(32) >>> (32 - n))).toUnsigned(32);
}

/// xorshift32 pseudo-random generator, kept within 32 bits.
int xorshift32(int s) {
  s ^= (s << 13) & 0xFFFFFFFF;
  s ^= s >>> 17;
  s ^= (s << 5) & 0xFFFFFFFF;
  return s;
}

const jsNumbers = identical(1, 1.0); // true only when compiled to JS

void main() {
  print('JS numbers: $jsNumbers');
  final data = utf8.encode('hello, bits');
  print('naive  ${fnv1aNaive(data).toRadixString(16)}');
  print('fnv1a  ${fnv1a(data).toRadixString(16)}');
  print('rotl   ${rotl32(0x80000001, 4).toRadixString(16)} '
      '${rotl32(0xABCD, 0).toRadixString(16)}');
  var s = 2463534242;
  final rolls = <int>[];
  for (var i = 0; i < 4; i++) {
    s = xorshift32(s);
    rolls.add(s);
  }
  print('xorshift $rolls');
}

Dart VM and WebAssembly (identical output):

JS numbers: false
naive  169ec20b
fnv1a  169ec20b
rotl   18 abcd
xorshift [723471715, 2497366906, 2064144800, 2008045182]

JavaScript:

JS numbers: true
naive  e1c7148c
fnv1a  169ec20b
rotl   18 abcd
xorshift [723471715, 2497366906, 2064144800, 2008045182]

The naive hash is wrong in JavaScript because the product loses its low bits before the mask is applied. mul32 multiplies the low and high 16-bit halves separately, so no intermediate result exceeds 2^49, and gives the same hash everywhere. The rotation and xorshift generator need no change because they already mask to 32 bits.

identical(1, 1.0) is a constant that is true only when compiled to JavaScript, where integers and doubles are the same objects. It's a handy way to pick a code path, though writing code that is correct on both, as above, is usually better. More differences between platforms are in Common pitfalls and BigInt on the web.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents