bits.dart 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. part of tri;
  2. class Bits {
  3. List<Tril> _trits;
  4. void clear() {
  5. _trits = new List(27);
  6. for (int i = 0; i < 27; i++) _trits[i] = NULL;
  7. }
  8. void _fill(int x, int mx){
  9. clear();
  10. List<int> m = new List(mx);
  11. int sign = x.toInt().sign;
  12. int r = x.abs();
  13. int i = 0;
  14. if (sign != 0) {
  15. do {
  16. int s = r % 3;
  17. r = r ~/ 3;
  18. if (s > 1) {
  19. r++;
  20. m[i] = s - 3;
  21. } else {
  22. m[i] = s;
  23. }
  24. i++;
  25. } while (!(r < 3));
  26. if (r > 1) {
  27. m[i] = r - 3;
  28. m[i + 1] = 1;
  29. i = i + 2;
  30. } else {
  31. m[i] = r;
  32. i++;
  33. }
  34. do {
  35. i--;
  36. _trits[i] = new Tril.fromInt(sign * m[i]);
  37. } while (i != 0);
  38. }
  39. }
  40. int _toInt(){
  41. int ret = _trits[0].toInt;
  42. for (int i=1; i<_trits.length; i++){
  43. ret = ret+(_trits[i].toInt*pow(3, i));
  44. }
  45. return ret;
  46. }
  47. int27 toInt27(){
  48. return new int27(_toInt());
  49. }
  50. Bits.fromTryte(tryte x) {
  51. _fill(x.toInt(), 9);
  52. }
  53. Bits.fromInt27(int27 x) {
  54. _fill(x.toInt(), 27);
  55. }
  56. @override
  57. String toString(){
  58. String ret = "]";
  59. _trits.forEach((t){
  60. if(t.True)
  61. ret = "+" + ret;
  62. else if(t.False)
  63. ret = "-" + ret;
  64. else
  65. ret = "0" + ret;
  66. });
  67. return '['+ret;
  68. }
  69. factory Bits(tri_num x) {
  70. if (x is tryte) return new Bits.fromTryte(x); else if (x is int27) return new Bits.fromInt27(x);
  71. }
  72. }