BinaryInt extension

A collection of unchecked binary methods to be applied to a 32-bit int.

There are a small subset of methods that support integers > 32-bits:

Other methods (as documented) have undefined behavior when operating on larger integers. It is instead recommended to

NOTE: There is limited range checking in this function. To verify accessing a valid bit use one of the Integral.getBit implementations, which knows both the minimum and maximum number of bits.

For example:

// Unchecked. We assume 'bits' is meant to represent at least 7 bits.
void example1(int bits) {
  print(bits.getBit(7));
}

// Checked. Will throw a RangeError because Int4 cannot have 7 bits.
void example2(Int4 bits) {
  print(bits.getBit(7));
}

Warnings for Dart2JS

When running compiled to JavaScript, an alternative set of operations are used for integers or operations that exceed 32-bits, which may be noticeably slower. In addition, integers or operations that exceed 52-bits may throw an UnsupportedError instead of undefined behavior.

on

Methods

bitChunk(int left, int size) int
Returns an int containining bits exclusive of the last bit.
bitRange(int left, int right) int
Returns an int containining bits inclusive of the last bit.
clearBit(int n) int
Returns a new int with the nth bit cleared.
countSetBits(int bitWidth) int
Returns the number of set bits in this, assuming a bitWidththis.
getBit(int n) int
Returns 1 if nth is bit set, else 0.
hiLo() Uint32List
Returns the current int split into an array of two elements where:
isClear(int n) bool
Returns whether bit n is cleared (i.e. 0).
isSet(int n) bool
Returns whether bit n is set (i.e. 1).
msb(int bitWidth) bool
Returns whether the most-significant-bit in this (of bitWidth) is set.
pow(int expontent) int
Returns this to the power of the provided expontent.
replaceBitRange(int left, int right, int bits) int
Returns an int replacing the bits from left to right with bits.
rotateRightShift(int r, int bitWidth) int
Returns a bit-wise right-rotation on this by an r of bits.
setBit(int n) int
Returns a new int with the nth bit set.
signedRightShift(int n, int bitWidth) int
Returns this right-shifted by n bytes assuming bitWidth.
signExtend(int startSize, int endSize) int
Returns this sign-extended to endSize bits.
toBinary() String
Returns this as a binary string representation.
toBinaryPadded(int bitWidth) String
Returns this as a binary string representation, padded with 0's.
toggleBit(int n, [bool? v]) int
Returns a new int with the nth bit toggled.