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:
- msb
- getBit
- setBit and isSet
- clearBit and isClear
- toggleBit
- countSetBits
- bitRange and bitChunk
- hiLo
- toBinary and toBinaryPadded
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
n
th bit cleared. -
countSetBits(
int bitWidth) → int -
Returns the number of set bits in
this
, assuming abitWidth
this
. -
getBit(
int n) → int -
Returns
1
ifn
th is bit set, else0
. -
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
(ofbitWidth
) is set. -
pow(
int expontent) → int -
Returns
this
to the power of the providedexpontent
. -
replaceBitRange(
int left, int right, int bits) → int -
Returns an int replacing the bits from
left
toright
withbits
. -
rotateRightShift(
int r, int bitWidth) → int -
Returns a bit-wise right-rotation on
this
by anr
of bits. -
setBit(
int n) → int -
Returns a new int with the
n
th bit set. -
signedRightShift(
int n, int bitWidth) → int -
Returns
this
right-shifted byn
bytes assumingbitWidth
. -
signExtend(
int startSize, int endSize) → int -
Returns
this
sign-extended toendSize
bits. -
toBinary(
) → String -
Returns
this
as a binary string representation. -
toBinaryPadded(
int bitWidth) → String -
Returns
this
as a binary string representation, padded with0
's. -
toggleBit(
int n, [bool? v]) → int -
Returns a new int with the
n
th bit toggled.