Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Bit-Manipulation/BitwiseParityCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
author: Hardvan

This script will check whether the given
number is even parity or odd parity.

Even parity is a property of binary numbers,
where the total number of 1-bits in a number
is even or odd.

Reference link: https://en.wikipedia.org/wiki/Parity_bit

If we will right shift the number by 1 bit
and XOR it with the original number, the
result will be 0 if the number has even parity
and 1 if the number has odd parity.

*/
export const checkEvenParity = (number) => {
let count = 0
while (number > 0) {
count ^= number & 1 // XOR operation to count set bits
number >>= 1 // Right shift to check the next bit
}
return count === 0 // Even parity if count is 0
}

export const checkOddParity = (number) => {
return !checkEvenParity(number) // Odd parity is the opposite of even parity
}
45 changes: 45 additions & 0 deletions Bit-Manipulation/test/BitwiseParityCheck.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { checkEvenParity, checkOddParity } from '../BitwiseParityCheck'

// Test cases for checkEvenParity
describe('checkEvenParity', () => {
it('should return true for a binary number with even parity', () => {
const binaryNumber = parseInt('1101100', 2) // Even parity binary number
const result = checkEvenParity(binaryNumber)
expect(result).toBe(true)
})

it('should return false for a binary number with odd parity', () => {
const binaryNumber = parseInt('1101101', 2) // Odd parity binary number
const result = checkEvenParity(binaryNumber)
expect(result).toBe(false)
})

it('should return true for a binary number with all bits set to 0', () => {
const binaryNumber = 0 // All bits set to 0
const result = checkEvenParity(binaryNumber)
expect(result).toBe(true)
})

// Add more test cases as needed
})

// Test cases for checkOddParity
describe('checkOddParity', () => {
it('should return true for a binary number with odd parity', () => {
const binaryNumber = parseInt('1101101', 2) // Odd parity binary number
const result = checkOddParity(binaryNumber)
expect(result).toBe(true)
})

it('should return false for a binary number with even parity', () => {
const binaryNumber = parseInt('1101100', 2) // Even parity binary number
const result = checkOddParity(binaryNumber)
expect(result).toBe(false)
})

it('should return true for a binary number with all bits set to 0', () => {
const binaryNumber = 0 // All bits set to 0
const result = checkEvenParity(binaryNumber)
expect(result).toBe(true)
})
})