Calculating and adding the parity bit to a binary using JavaScript

A parity bit, or check bit, is a bit added to a string of bits to ensure that the total number of 1-bits in the string is even or odd. This is commonly used in error detection and data transmission.

Problem Statement

We need to write a JavaScript function that takes two parameters: the desired parity (either 'even' or 'odd') and a binary string representation. The function should return the parity bit (0 or 1) that needs to be added to achieve the specified parity.

How Parity Bits Work

Even Parity Example: Binary: 0101010 (3 ones - odd) Add bit: 1 ? 01010101 (4 ones - even) Odd Parity Example: Binary: 1100110 (4 ones - even) Add bit: 1 ? 11001101 (5 ones - odd)

Solution

const parity = 'even';
const bin = '0101010';

const findParity = (parity, bin) => {
    const arr = bin.toString().split("");
    let countOnes = 0;
    let res = 0;
    
    // Count the number of 1s in the binary string
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == 1) {
            countOnes += 1;
        }
    }
    
    // Determine parity bit based on desired parity
    if (parity == 'even') {
        if (countOnes % 2 == 0) {
            res = 0; // Already even, add 0
        } else {
            res = 1; // Odd count, add 1 to make even
        }
    } else {
        if (countOnes % 2 !== 0) {
            res = 0; // Already odd, add 0
        } else {
            res = 1; // Even count, add 1 to make odd
        }
    }
    
    return res;
};

console.log(findParity(parity, bin));
1

Alternative Implementation

Here's a more concise version using array methods:

const findParityBit = (parity, bin) => {
    // Count 1s using filter
    const onesCount = bin.split('').filter(bit => bit === '1').length;
    const isOdd = onesCount % 2 === 1;
    
    // Return appropriate parity bit
    return (parity === 'even') ? (isOdd ? 1 : 0) : (isOdd ? 0 : 1);
};

// Test with different examples
console.log(findParityBit('even', '0101010')); // 1
console.log(findParityBit('odd', '1100110'));  // 1
console.log(findParityBit('even', '1111'));    // 0
1
1
0

Comparison of Approaches

Method Readability Performance Lines of Code
For Loop Good Faster More
Array Methods Excellent Slightly slower Fewer

Key Points

  • Even parity: Total number of 1s should be even
  • Odd parity: Total number of 1s should be odd
  • The parity bit is added to achieve the desired parity
  • Returns 0 if no additional bit needed, 1 if one bit needed

Conclusion

Parity bits are essential for error detection in digital systems. The function counts existing 1s and determines whether to add 0 or 1 to achieve the desired even or odd parity.

Updated on: 2026-03-15T23:19:00+05:30

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements