Skip to content

Instantly share code, notes, and snippets.

@Jeongseup
Last active June 25, 2023 14:14
Show Gist options
  • Save Jeongseup/393043de1ad18b3f1dd92fa01beb744d to your computer and use it in GitHub Desktop.
Save Jeongseup/393043de1ad18b3f1dd92fa01beb744d to your computer and use it in GitHub Desktop.
pragma circom 2.1.4;
template Num2Bits(nBits) {
signal input x;
signal output b[nBits];
for (var i = 0; i < nBits; i++) {
b[i] <-- x \ (2 ** i) % 2;
}
for (var i = 0; i < nBits; i++) {
b[i] * (b[i] - 1) === 0;
}
var accum = 0;
for (var i = 0; i < nBits; i++) {
accum += 2 ** i * b[i];
}
accum === x;
}
// input is a field element from [0, 16)
// output four signals b0b1b2b3 representing the binary repr of input
template Num2FourBits () {
signal input x;
signal output b0;
signal output b1;
signal output b2;
signal output b3;
b0 <-- x % 2;
b1 <-- x \ 2 % 2;
b2 <-- x \ 4 % 2;
b3 <-- x \ 8 % 2;
b0 * (b0 - 1) === 0;
b1 * (b1 - 1) === 0;
b2 * (b2 - 1) === 0;
b3 * (b3 - 1) === 0;
1*b0 + 2*b1 + 4*b2 + 8*b3 === x;
// log("x", x);
}
component main { public [ x ] } = Num2Bits(4);
/* INPUT = {
"x": "11"
} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment