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    for (var i = 0; i<n; i++) {
 30        out[i] <-- (in >> i) & 1;
 31        out[i] * (out[i] -1 ) === 0;
 32        lc1 += out[i] * 2**i;
 33    }
 34
 35    lc1 === in;
 36}
 37
 38template Num2Bits_strict() {
 39    signal input in;
 40    signal output out[254];
 41
 42    component aliasCheck = AliasCheck();
 43    component n2b = Num2Bits(254);
 44    in ==> n2b.in;
 45
 46    for (var i=0; i<254; i++) {
 47        n2b.out[i] ==> out[i];
 48        n2b.out[i] ==> aliasCheck.in[i];
 49    }
 50}
 51
 52template Bits2Num(n) {
 53    signal input in[n];
 54    signal output out;
 55    var lc1=0;
 56
 57    for (var i = 0; i<n; i++) {
 58        lc1 += in[i] * 2**i;
 59    }
 60
 61    lc1 ==> out;
 62}
 63
 64template Bits2Num_strict() {
 65    signal input in[n];
 66    signal output out;
 67
 68    component aliasCheck = AliasCheck();
 69    component b2n = Bits2Num(254);
 70
 71    for (var i=0; i<254; i++) {
 72        in[i] ==> b2n.in[i];
 73        in[i] ==> aliasCheck.in[i];
 74    }
 75
 76    b2n.out ==> out;
 77}
 78
 79template Num2BitsNeg(n) {
 80    signal input in;
 81    signal output out[n];
 82    var lc1=0;
 83
 84    component isZero;
 85
 86    isZero = IsZero();
 87
 88    var neg = n == 0 ? 0 : 2**n - in;
 89
 90    for (var i = 0; i<n; i++) {
 91        out[i] <-- (neg >> i) & 1;
 92        out[i] * (out[i] -1 ) === 0;
 93        lc1 += out[i] * 2**i;
 94    }
 95
 96    in ==> isZero.in;
 97
 98
 99
100    lc1 + isZero.out * 2**n === 2**n - in;
101}