From f84c4c92a18a7b919910b2ed3fe3aa664c10e8e0 Mon Sep 17 00:00:00 2001 From: aadil42 <77232799+aadil42@users.noreply.github.com> Date: Wed, 2 Aug 2023 16:35:59 +0530 Subject: [PATCH] Create ones_complement_checksum16bit.js Adding a function that generates a checksum and a function that checks the sum for data integrity. --- .../ones_complement_checksum16bit.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 02. Algorithms/09. Checksum Calc/ones_complement_checksum16bit.js diff --git a/02. Algorithms/09. Checksum Calc/ones_complement_checksum16bit.js b/02. Algorithms/09. Checksum Calc/ones_complement_checksum16bit.js new file mode 100644 index 00000000..029cb7c0 --- /dev/null +++ b/02. Algorithms/09. Checksum Calc/ones_complement_checksum16bit.js @@ -0,0 +1,36 @@ + +const checksumCalc = (data) => { + + // adding all the bytes + const total = data.reduce((acc, num) => { + return acc + num; + }); + + // taking inverse of the total + const totalInverse = total ^ ~0; + + // appending the inversed byte at the end. + data.push(totalInverse); + + // tinkering with a byte to simulate the data change + // data[3] = 22; + return data; +} + +const checksum = (data) => { + + let total = 0; + for(let i = 0; i < data.length - 1; i++) { + total += data[i]; + } + + const inverseTotal = total ^ data[data.length - 1]; + + // inverseTotal should Have all bytes set to one. negeting it should give us 0. If it's 0 then the data is safe. + return ~inverseTotal === 0; +} + + +// data is an array of numbers +const data = [12,34,54,66,90]; +console.log(checksum(checksumCalc(data)));