I want to perform bitwise operations on any two buffers representing 64 bit unsigned ints. I apparently enjoy suffering so I decided to try this in JavaScript, which doesn't even support 64 bit math without BigInt conversion (which is not in my code yet). I know I must be approaching this in the most naïve, horrible way, but here it is.
The code doesn't get the right answer, but that's not really the problem. More like the way I'm going about it feels very inefficient. I knew I must be approaching the whole thing wrong so I stopped fixing this dumpster-fire of a function to ask the right way to do it. You'll get the idea:
function printHexStr(arr) {
return Array.from(arr)
.map((x) => {
return x.toString(16).padStart(2, "0");
})
.join(" ");
}
function consolidateBuffer(buffer) {
let val;
let bufferDigits = []
for (let i = 0; i < buffer.length; i++) {
let digits = buffer[i].toString(16).split('')
digits.forEach((digitStr, index) => {
digits[index] = parseInt(digitStr, 16)
})
console.log('digits', digits)
bufferDigits.push(...digits)
}
console.log('bufferDigits', bufferDigits)
let list = []
for (let i = bufferDigits.length - 1, j = 0; i >= 0; i--, j++) {
console.log('i', i)
console.log("bufferDigits[i]", bufferDigits[i], '{', bufferDigits[i].toString(16), '}');
if (i == bufferDigits.length - 1) {
val = bufferDigits[i];
} else {
console.log('val{', val, '} += bufferDigits[i]{', bufferDigits[i], '} * j{', j, '}^16{', Math.pow(16, j), '} == ', bufferDigits[i] * Math.pow(16, j))
val += bufferDigits[i] * Math.pow(16, j);
}
list.push(bufferDigits[i].toString(16))
console.log("list:", printHexStr(list), "=> val:", val);
}
console.log("Consolidated buffer:", bufferDigits, "to", val);
return val;
}
let buff = new Uint8Array([0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f])
consolidateBuffer(buff)
The expected output would be 2242545357980376863. Someone please teach me a method of doing this that's less of a sin against mankind.
I would like to optionally input smaller buffers for 8, 16, 32 bit unsigned ints too.