2008-10-22 14:02:58 +00:00
|
|
|
var bit = [var _ = 1];
|
2008-10-22 12:49:01 +00:00
|
|
|
for (var i = 1; i < 32; i += 1)
|
2008-10-22 14:02:58 +00:00
|
|
|
append(bit, _ += _);
|
2008-10-22 12:49:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
# checks whether bit <b> is set in number <n>
|
|
|
|
var test = func(n, b) {
|
2008-10-22 14:02:58 +00:00
|
|
|
n /= bit[b];
|
|
|
|
return int(n) != int(n / 2) * 2;
|
2008-10-22 12:49:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# returns number <n> with bit <b> set
|
2008-10-22 23:27:03 +00:00
|
|
|
var set = func(n, b) n + !test(n, b) * bit[b];
|
2008-10-22 12:49:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
# returns number <n> with bit <b> cleared
|
2008-10-22 23:04:07 +00:00
|
|
|
var clear = func(n, b) n - test(n, b) * bit[b];
|
2008-10-22 20:56:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
# returns number <n> with bit <b> toggled
|
|
|
|
var toggle = func(n, b) test(n, b) ? n - bit[b] : n + bit[b];
|
|
|
|
|
|
|
|
|
|
|
|
# returns number <n> with bit <b> set to value <v>
|
|
|
|
var switch = func(n, b, v) n - (test(n, b) - !!v) * bit[b];
|
|
|
|
|
2008-10-23 22:16:32 +00:00
|
|
|
|
|
|
|
# returns number <n> as bit string, zero-padded to <len> digits:
|
|
|
|
# bits.string(6) -> "110"
|
|
|
|
# bits.string(6, 8) -> "00000110"
|
2008-12-22 01:50:48 +00:00
|
|
|
var string = func(n, len = 1) {
|
2008-10-23 22:16:32 +00:00
|
|
|
var s = "";
|
|
|
|
while (n) {
|
2008-10-25 15:03:32 +00:00
|
|
|
var v = int(n / 2);
|
|
|
|
s = (v + v != n) ~ s;
|
2008-10-23 22:16:32 +00:00
|
|
|
n = v;
|
|
|
|
}
|
|
|
|
for (var i = size(s); i < len; i += 1)
|
|
|
|
s = '0' ~ s;
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2008-10-25 15:03:32 +00:00
|
|
|
# returns bit string <s> as number: bits.value("110") -> 6
|
|
|
|
var value = func(s) {
|
|
|
|
var n = 0;
|
|
|
|
var len = size(s);
|
|
|
|
for (var i = 0; i < len; i += 1)
|
|
|
|
n += n + (s[i] != `0`);
|
|
|
|
return n;
|
|
|
|
}
|
|
|
|
|
|
|
|
|