From 6d5585ec65f343ad3d35cc7fd55363cc18a3b91c Mon Sep 17 00:00:00 2001 From: mfranz Date: Wed, 22 Oct 2008 12:49:01 +0000 Subject: [PATCH] restore simple bits functions. Useful for setting/testing boolean values inr MP transport, and for setting/clearing modifier bits in js config files. --- Nasal/bits.nas | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Nasal/bits.nas diff --git a/Nasal/bits.nas b/Nasal/bits.nas new file mode 100644 index 000000000..609313874 --- /dev/null +++ b/Nasal/bits.nas @@ -0,0 +1,37 @@ +var _bits = [var _ = 1]; +for (var i = 1; i < 32; i += 1) + append(_bits, _ += _); + + +# returns number 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 is set in number +# +var test = func(n, b) { + while (b) { + n /= 2; + b -= 1; + } + int(n) != int(n / 2) * 2; +} + + +# returns number with bit set +# +var set = func(n, b) test(n, b) ? n : n + _bits[b]; + + +# returns number with bit cleared +# +var clear = func(n, b) test(n, b) ? n - _bits[b] : n;