From 476e5b166c8e503ac538e8fe7321676a02d6edbc Mon Sep 17 00:00:00 2001 From: USP-2024 Date: Sun, 13 Oct 2024 17:40:29 +0530 Subject: [PATCH] Update add_binary.ts TypeScript code snippet that converts a Binary-Coded Decimal (BCD) to Gray code and also converts a decimal number to BCD. --- bit_manipulation/add_binary.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/bit_manipulation/add_binary.ts b/bit_manipulation/add_binary.ts index 7e6ecd03..bfd6540d 100644 --- a/bit_manipulation/add_binary.ts +++ b/bit_manipulation/add_binary.ts @@ -26,6 +26,35 @@ export function addBinary( lengthOfSecondNumber-- } + // Function to convert BCD to Gray code +const bcdToGray = (bcd: string): string => { + let gray = ''; + gray += bcd[0]; // The most significant bit remains the same + + for (let i = 1; i < bcd.length; i++) { + gray += (bcd[i] === bcd[i - 1]) ? '0' : '1'; + } + + return gray; +}; + +// Function to convert decimal to BCD +const decimalToBCD = (decimal: number): string => { + return decimal.toString().split('').map(num => { + return parseInt(num).toString(2).padStart(4, '0'); // Convert to binary and pad with zeros + }).join(''); +}; + +// Example usage +const decimalNumber = 45; +const bcd = decimalToBCD(decimalNumber); +const grayCode = bcdToGray(bcd); + +console.log(`Decimal: ${decimalNumber}`); +console.log(`BCD: ${bcd}`); +console.log(`Gray Code: ${grayCode}`); + + if (carry !== 0) solution.push(carry.toString()) return solution.reverse().join('')