Skip to content

Instantly share code, notes, and snippets.

@Ephellon
Created June 7, 2020 16:08
Show Gist options
  • Save Ephellon/ba99e0e9d229abbda8ffc64313b6cfad to your computer and use it in GitHub Desktop.
Save Ephellon/ba99e0e9d229abbda8ffc64313b6cfad to your computer and use it in GitHub Desktop.
Simple function for adding an arbitrary number of bits
/** addBits(A, B, S?)
* @param A The first set of bits
{ BigInt | Number | String === /^[01]*$/ | Object == Array }
* @param B The second set of bits
{ BigInt | Number | String === /^[01]*$/ | Object == Array }
* @param S The signature boolean
= true -> Use signed mode (int)
= false -> Use unsigned mode (uint)
* @return String === /^[01]+$/
*/
function addBits(A, B, S = false) {
let O = [];
if(typeof A == 'number')
A = A.toString(2);
if(typeof A == 'string')
A = A.split('');
if(typeof A == 'object' && A.map)
A = A.map(x => parseInt(x));
if(typeof B == 'number')
B = B.toString(2);
if(typeof B == 'string')
B = B.split('');
if(typeof B == 'object' && B.map)
B = B.map(x => parseInt(x));
A = A.reverse();
B = B.reverse();
let c = 0;
for(let i = 0, l = Math.max(A.length, B.length); i < l; i++) {
let a = A[i] | 0,
b = B[i] | 0;
console.log({ a, b, c, i });
if(!i) {
c = a & b;
O.push(a ^ b);
} else {
O.push((a ^ b) ^ c);
c = (a & b) | (a & c);
}
}
if(S)
O.push(c);
return O.reverse().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment