Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create ones_complement_checksum16bit.js #581

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions 02. Algorithms/09. Checksum Calc/ones_complement_checksum16bit.js
Original file line number Diff line number Diff line change
@@ -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)));