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

TypeScript BCD TO GRAY AND DECIMAL TO BCD Update add_binary.ts #263

Open
wants to merge 1 commit into
base: master
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
29 changes: 29 additions & 0 deletions bit_manipulation/add_binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('')
Expand Down