Skip to content

Instantly share code, notes, and snippets.

@Allan-Nava
Last active May 2, 2019 14:14
Show Gist options
  • Save Allan-Nava/347233376d1bde2abdde67f265e9dd5d to your computer and use it in GitHub Desktop.
Save Allan-Nava/347233376d1bde2abdde67f265e9dd5d to your computer and use it in GitHub Desktop.
to Bits
// Allan Nava snippet code
import 'dart:math' as math;
void main() {
var value = toBits(3039003383);
print(value);
}
///
static double toBits(int bits) {
var sizes = ['bps', 'Kbit/s', 'Mbit/s', 'Gbit/s', 'Tbit/s'];
if(bits <= 0) return 0;
var bits_log1000 = math.log(bits) / math.log(1000);
print("bits_log1000: $bits_log1000 ");
var i = (bits_log1000).floor();
print("i: $i ");
if (i < 0 || i.isNaN) {
i = 0;
} else if (i >= sizes.length) { // prevents overflows
return 0;
}
///
if (i <= 1) {
var d = ((bits / math.pow(1000, i) * 100) / 100).toStringAsFixed(2);
print("i<=1 ====> d: $d ");
return double.parse(d);
} else {
var ret = double.parse((bits / math.pow(1000, i)).toStringAsFixed(2));
print("ret: $ret");
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment