Created
July 13, 2020 19:55
-
-
Save matanlurey/0d779f2cae87c5305c63195791b500a2 to your computer and use it in GitHub Desktop.
Check if a bit is set (or not) in Dart, compiled to JS, working with >32-bit integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math' as math; | |
void main() { | |
final maxUint = 0xffffffff; | |
final longRes = maxUint + maxUint; | |
print('As Hex : ' + longRes.toRadixString(16)); | |
print('As Binary: ' + longRes.toRadixString(2)); | |
print('Bit 31 : ' + longRes.getBit(31).toString()); | |
print('Bit 32 : ' + longRes.getBit(32).toString()); | |
} | |
extension on int { | |
int getBit(int n) { | |
return n < 32 ? _getBitSmi(n) : _getBitLng(n); | |
} | |
int _logAndLng(int o) { | |
const hi = 0x80000000; | |
const lo = 0x7fffffff; | |
final h1 = ~~(this ~/ hi); | |
final h2 = ~~(o ~/ hi); | |
final l1 = this & lo; | |
final l2 = o & lo; | |
final hr = h1 & h2; | |
final lr = l1 & l2; | |
return hr * hi + lr; | |
} | |
int _getBitLng(int n) { | |
final rhs = math.pow(2, n) as int; | |
return _logAndLng(rhs) == 0 ? 0 : 1; | |
} | |
int _getBitSmi(int n) => (this & (1 << n)) == 0 ? 0 : 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment