1
0
Fork 0

bits.string: add optional zero-padding

This commit is contained in:
mfranz 2008-10-23 22:16:32 +00:00
parent 97c1ec0ac7
commit 6371627424

View file

@ -3,19 +3,6 @@ for (var i = 1; i < 32; i += 1)
append(bit, _ += _);
# returns number <n> as bit string: bits.string(6) -> "110"
var string = func(n) {
if (!n)
return '0';
var s = "";
while (n) {
s = ((var v = int(n / 2)) + v != n) ~ s;
n = v;
}
return s;
}
# checks whether bit <b> is set in number <n>
var test = func(n, b) {
n /= bit[b];
@ -38,3 +25,21 @@ 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];
# returns number <n> as bit string, zero-padded to <len> digits:
# bits.string(6) -> "110"
# bits.string(6, 8) -> "00000110"
var string = func(n, len = 0) {
if (!n)
return '0';
var s = "";
while (n) {
s = ((var v = int(n / 2)) + v != n) ~ s;
n = v;
}
for (var i = size(s); i < len; i += 1)
s = '0' ~ s;
return s;
}