You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.4 KiB

6 years ago
  1. /*
  2. Binary Sum
  3. ==========
  4. This component creates a binary sum componet of ops operands and n bits each operand.
  5. e is Number of carries: Depends on the number of operands in the input.
  6. Main Constrain:
  7. in[0][0] * 2^0 + in[0][1] * 2^1 + ..... + in[0][n-1] * 2^(n-1) +
  8. + in[1][0] * 2^0 + in[1][1] * 2^1 + ..... + in[1][n-1] * 2^(n-1) +
  9. + ..
  10. + in[ops-1][0] * 2^0 + in[ops-1][1] * 2^1 + ..... + in[ops-1][n-1] * 2^(n-1) +
  11. ===
  12. out[0] * 2^0 + out[1] * 2^1 + + out[n+e-1] *2(n+e-1)
  13. To waranty binary outputs:
  14. out[0] * (out[0] - 1) === 0
  15. out[1] * (out[0] - 1) === 0
  16. .
  17. .
  18. .
  19. out[n+e-1] * (out[n+e-1] - 1) == 0
  20. */
  21. /*
  22. This function calculates the number of extra bits in the output to do the full sum.
  23. */
  24. function nbits(a) {
  25. var n = 1;
  26. var r = 0;
  27. while (n-1<a) {
  28. r++;
  29. n *= 2;
  30. }
  31. return r;
  32. }
  33. template BinSum(n, ops) {
  34. var nout = nbits((2**n -1)*ops);
  35. signal input in[ops][n];
  36. signal output out[nout];
  37. var lin = 0;
  38. var lout = 0;
  39. var k;
  40. var j;
  41. for (k=0; k<n; k++) {
  42. for (j=0; j<ops; j++) {
  43. lin += in[j][k] * 2**k;
  44. }
  45. }
  46. for (k=0; k<nout; k++) {
  47. out[k] <-- (lin >> k) & 1;
  48. // Ensure out is binary
  49. out[k] * (out[k] - 1) === 0;
  50. lout += out[k] * 2**k;
  51. }
  52. // Ensure the sum;
  53. lin === lout;
  54. }