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";
21
22
23template Num2Bits(n) {
24    signal input in;
25    signal output out[n];
26    var lc1=0;
27
28    for (var i = 0; i<n; i++) {
29        out[i] <-- (in >> i) & 1;
30        out[i] * (out[i] -1 ) === 0;
31        lc1 += out[i] * 2**i;
32    }
33
34    lc1 === in;
35
36}
37
38template Bits2Num(n) {
39    signal input in[n];
40    signal output out;
41    var lc1=0;
42
43    for (var i = 0; i<n; i++) {
44        lc1 += in[i] * 2**i;
45    }
46
47    lc1 ==> out;
48}
49
50template Num2BitsNeg(n) {
51    signal input in;
52    signal output out[n];
53    var lc1=0;
54
55    component isZero;
56
57    isZero = IsZero();
58
59    var neg = n == 0 ? 0 : 2**n - in;
60
61    for (var i = 0; i<n; i++) {
62        out[i] <-- (neg >> i) & 1;
63        out[i] * (out[i] -1 ) === 0;
64        lc1 += out[i] * 2**i;
65    }
66
67    in ==> isZero.in;
68
69
70
71    lc1 + isZero.out * 2**n === 2**n - in;
72}