arnaucube
arnaucube/circomlibPublic Self-hosted repository
circomlib/circuits/bitify.circom
circuits/bitify.circomRaw
  1/*
  2    Copyright 2018 0KIMS association.
  3
  4    This file is part of circom (Zero Knowledge Circuit Compiler).
  5
  6    circom is a free software: you can redistribute it and/or modify it
  7    under the terms of the GNU General Public License as published by
  8    the Free Software Foundation, either version 3 of the License, or
  9    (at your option) any later version.
 10
 11    circom is distributed in the hope that it will be useful, but WITHOUT
 12    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 13    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 14    License for more details.
 15
 16    You should have received a copy of the GNU General Public License
 17    along with circom. If not, see <https://www.gnu.org/licenses/>.
 18*/
 19
 20include "comparators.circom";
 21include "aliascheck.circom";
 22
 23
 24template Num2Bits(n) {
 25    signal input in;
 26    signal output out[n];
 27    var lc1=0;
 28
 29    var e2=1;
 30    for (var i = 0; i<n; i++) {
 31        out[i] <-- (in >> i) & 1;
 32        out[i] * (out[i] -1 ) === 0;
 33        lc1 += out[i] * e2;
 34        e2 = e2+e2;
 35    }
 36
 37    lc1 === in;
 38}
 39
 40template Num2Bits_strict() {
 41    signal input in;
 42    signal output out[254];
 43
 44    component aliasCheck = AliasCheck();
 45    component n2b = Num2Bits(254);
 46    in ==> n2b.in;
 47
 48    for (var i=0; i<254; i++) {
 49        n2b.out[i] ==> out[i];
 50        n2b.out[i] ==> aliasCheck.in[i];
 51    }
 52}
 53
 54template Bits2Num(n) {
 55    signal input in[n];
 56    signal output out;
 57    var lc1=0;
 58
 59    var e2 = 1;
 60    for (var i = 0; i<n; i++) {
 61        lc1 += in[i] * e2;
 62        e2 = e2 + e2;
 63    }
 64
 65    lc1 ==> out;
 66}
 67
 68template Bits2Num_strict() {
 69    signal input in[n];
 70    signal output out;
 71
 72    component aliasCheck = AliasCheck();
 73    component b2n = Bits2Num(254);
 74
 75    for (var i=0; i<254; i++) {
 76        in[i] ==> b2n.in[i];
 77        in[i] ==> aliasCheck.in[i];
 78    }
 79
 80    b2n.out ==> out;
 81}
 82
 83template Num2BitsNeg(n) {
 84    signal input in;
 85    signal output out[n];
 86    var lc1=0;
 87
 88    component isZero;
 89
 90    isZero = IsZero();
 91
 92    var neg = n == 0 ? 0 : 2**n - in;
 93
 94    for (var i = 0; i<n; i++) {
 95        out[i] <-- (neg >> i) & 1;
 96        out[i] * (out[i] -1 ) === 0;
 97        lc1 += out[i] * 2**i;
 98    }
 99
100    in ==> isZero.in;
101
102
103
104    lc1 + isZero.out * 2**n === 2**n - in;
105}